String problems

Okay, in my application it asks for name and age, but if they put John Trub, it messes up, they have to put one name either John, or Trub, if they add the space then the application skips all the way to your age and says your age is 0 right? Here is the code.

1
2
3
4
5
6
7
8

std::cout << "Before we begin this adventerous 'Text Based Game', we need some things from the player(you). Please input your   name, it can be first name, last name, middle name, all three, or even a made up name." << std::endl;
std::cin >> name;
std::cout << "Now please enter your age. Using letters for your age may brake the             application and you will have to re-load it." << std::endl;
std::cin >> age;
std::cout << "Okay please verify that your name is " << name << ", " << "and your age is " << age << " " << "Right?" << std::endl;

The >> operator stops at whitespace. So if you enter "John Trub", extracting with >> will only get you "John", leaving the "Trub" in the buffer.... which you attempt (and fail) to read as an age.

Try getline:

1
2
// std::cin >> name; <- replace this
std::getline( std::cin, name );  // <- with this 
That skipped typing in the name completely and skipped to the age portion.
closed account (Dy7SLyTq)
write cin.flush(); above it
It says

D:\Pictures\Customtory(RPG)\main.cpp|15|error: 'std::istream' has no member named 'flush'|
closed account (Dy7SLyTq)
sorry my mistake i can never remember that its not right.

so instead write:
1
2
cin.clear();
cin.ignore(1024, '\n'); 


edit: i wrote edit at the beginning of my post for some reason...
Last edited on
Works great, but could you explain what the lines do?
closed account (Dy7SLyTq)
http://www.cplusplus.com/forum/beginner/107405/#msg582615
Topic archived. No new replies allowed.