views:

53

answers:

2
        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;

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?

+2  A: 

You can use getline():

cout << "Input street number: ";
cin.getline(streetnum, 256); // Assuming 256 character buffer...
cout << "Input street name: ";
cin.getline(streetname, 256);
Reed Copsey
Better would be to use a `std::string` and `std::getline` instead of hard-coding a buffer size.
GMan
@Gman: True - but this is at least fixes the problem at hand.
Reed Copsey
+7  A: 

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.

:)

GMan