C++ Gebruikersinvoerstrings


Strings voor gebruikersinvoer

Het is mogelijk om de extractie-operator >>aan cinte gebruiken om een ​​string weer te geven die door een gebruiker is ingevoerd:

Voorbeeld

string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John
// Your name is: John

Beschouwt een spatie (spatie , cintabs, enz.) echter als een afsluitend teken, wat betekent dat het slechts één woord kan weergeven (zelfs als u veel woorden typt):

Voorbeeld

string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe
// Your name is: John

Uit het bovenstaande voorbeeld zou je verwachten dat het programma "John Doe" afdrukt, maar het drukt alleen "John" af.

Daarom gebruiken we bij het werken met strings vaak de getline() functie om een ​​regel tekst te lezen. Het neemt cinals de eerste parameter en de stringvariabele als tweede:

Voorbeeld

string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: John Doe
// Your name is: John Doe