Backwards

This is a discussion on Backwards within the C++ Programming forums, part of the General Programming Boards category; How could I modify this program to output the tokens in reverse order? Code: #include <iostream> using std::cin; using std::cout; ...

  1. #1
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124

    Backwards

    How could I modify this program to output the tokens in reverse order?

    Code:
    #include <iostream>
    using std::cin;
    using std::cout;
    
    #include <cstring>
    
    void output( const int, char [] );
    
    int main() {
       
       const int Size = 50;
       char words[ Size ] = { '\0' }; 
       
       cin.getline( words, Size );
      
       output( Size, words );
       
       cin.get();
       return 0;
    }
    
    void output( const int Size, char sentence[] ) {
       
       char *strToken;
       int control = Size;
       
       strToken = strtok( sentence, " " );
       cout << '\n';
       
       while ( (strToken != NULL) ) {
          cout << strToken << '\n';
          strToken = strtok( NULL, " " );
       }
       
    }
    I've tried numerous things which haven't worked. Is pointer arith needed? Thanks.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    (Imitating Emeril Lagasse) Bam!
    Code:
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    void print_backward ( char *tok );
    
    int main()
    {
      char line[50]; 
    
      cin.getline ( line, sizeof line );
      print_backward ( strtok ( line, " " ) );
      cout<<endl;
    }
    
    void print_backward ( char *tok )
    {
      if ( tok == 0 )
        return;
      print_backward ( strtok ( 0, " " ) );
      cout<< tok <<' ';
    }
    Who says strtok can't be used recursively?
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Backwards uint16_t?
    By DavidDobson in forum C Programming
    Replies: 7
    Last Post: 05-11-2009, 09:45 AM
  2. Searching backwards in a string
    By Ducky in forum C++ Programming
    Replies: 11
    Last Post: 03-09-2008, 12:54 AM
  3. Oh noes, backwards she goes!
    By cboard_member in forum C++ Programming
    Replies: 8
    Last Post: 03-11-2006, 08:58 AM
  4. Taking input and Outputting it backwards
    By whtpirate in forum C Programming
    Replies: 9
    Last Post: 06-08-2003, 10:59 AM
  5. how to print a string backwards
    By Unregistered in forum C# Programming
    Replies: 2
    Last Post: 01-27-2002, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21