Member Avatar for dmmckelv

My while statement does not work. This program is only performing the function on the first word in the sentence. Can anyone help me get the while statement to do all of the words in the sentence?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include <cstring>
using std::strtok;
using std::strlen;


const int SIZE = 80;

// function prototype
void printLatinWord( char const * const  );

int main()
{
char sentence[ SIZE ];
char *tokenPtr;

cout << "Enter a sentence:\n";
cin >> sentence;

tokenPtr = strtok( sentence, " " );

while ( tokenPtr != NULL )
{
    printLatinWord( tokenPtr );
    tokenPtr = strtok( NULL , " " );//get next token
}
}

void printLatinWord ( char const * const tokenPtr )
{
    //cout << tokenPtr << " " <<strlen( tokenPtr ) << endl;
    long length = strlen( tokenPtr );
    char newWord[SIZE];
    int x = 0;
    
    for ( x=1 ; x <= length; x++)
    {
        newWord[x-1]= tokenPtr[length -(length - x)];
    }
    cout << newWord;
    cout <<  tokenPtr[0] << "ay ";
}

Thanks for the help!

>>cin >> sentence;
there is nothing wrong with that while loop. The problem is the line above -- the extraction operator >> stops at the first space. use getline() instead.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.