March 7th, 2013, 05:37 PM
Issue with the suffix increment operator(++) in a cout statement.
Hello, I am teaching myself C++ as a hobby and I encountered an example in the book which compiles but does not produce the intended output.
Here is the code:
// Creating and joining string objects
// List names and ages
void listnames(string names, string ages, size_t count)
size_t i = 0;
cout << endl << "The names you entered are: " << endl;
while(i<count && !names[i].empty())
cout << names[i] + " aged " + ages[i++] + '.' << endl;
const size_t count = 100;
for(size_t i = 0 ; i<count ; i++)
cout << endl << "Enter a first name or press Enter to end: ";
getline(cin, firstname, '\n');
listnames(names, ages, i);
cout << "Done!!" << endl;
cout << "Enter a second name: ";
getline(cin, secondname, '\n');
names[i] = firstname + ' ' + secondname;
cout << "Enter " + firstname + "'s age: ";
getline(cin, ages[i], '\n');
cout << "No space for more names." << endl;
listnames(names, ages, count);
I may be wrong, but the problem seems to be in the function "listnames". Specifically, the output statement inside the while loop. I don't understand
how the ++ operator is behaving in this statement. The output produced does not match what's printed in the book. I usually just type all the
examples, but with this one I also downloaded the source code from the book's website to make sure the error wasn't due to mistyping. I would
greatly appreciate any help that would explain what is going on.
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.