-
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.
-
(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? ;)