> streetnum; cout << "Input street name: "; cin >> s...">

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?

+3
source share
2 answers

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.

:)

+7

getline():

cout << "Input street number: ";
cin.getline(streetnum, 256); // Assuming 256 character buffer...
cout << "Input street name: ";
cin.getline(streetname, 256);
+2

Source: https://habr.com/ru/post/1740085/


All Articles