How to change this code in C ++ to make work better
cout << "Input street number: ";
cin >> streetnum;
cout << "Input street name: ";
cin >> streetname;
cout << "Input resource name: ";
cin >> rName;
cout << "Input architectural style: ";
cin >> aStyle;
cout << "Input year built: ";
cin >> year;
A problem with the above code occurs if you enter spaces between words. For example, if I enter Ampitheater Parkway for a street name, it places Ampithera in the street name, skips the invitation for the resource name and enters Parkway in the next field. How can i fix this?
This is because when you use the extract operator with a string as the right side, it stops at the first space character.
Do you want a getlinefree feature:
std::getline(std::cin, streetnum); // reads until \n
You can specify a different delimiter if you want:
char c = /* something */;
std::getline(std::cin, streetnum, c); // reads until c is encountered
:
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.
:)