cout << "Input street number: ";
cin >> streetnum;
cout << "Input street name: ";
cin >> streetname;
开发者_StackOverflow中文版 cout << "Input resource name: ";
cin >> rName;
cout << "Input architectural style: ";
cin >> aStyle;
cout << "Input year built: ";
cin >> year;
The problem with the above code happens if you enter in spaces between words. For example if I enter "Ampitheater Parkway" for streetname, then it puts "Ampitheater" in streetname, skips the prompt for resource name and enters "Parkway" into the next field. How can I fix this?
That's because when you use the extraction operator with a string as the right-hand side, it stops at the first white space character.
What you want is the getline
free function:
std::getline(std::cin, streetnum); // reads until \n
You can specify some other delimiter if you want:
char c = /* something */;
std::getline(std::cin, streetnum, c); // reads until c is encountered
Even better is to make a little function to use:
void prompt(const std::string& pMsg, std::string& pResult)
{
std::cout >> pMsg >> ": ";
std::getline(std::cin, pResult);
}
prompt("Street Number", streetnum);
prompt("Street Name", streetname);
// etc.
:)
You can use getline():
cout << "Input street number: ";
cin.getline(streetnum, 256); // Assuming 256 character buffer...
cout << "Input street name: ";
cin.getline(streetname, 256);
精彩评论