Stringhe di input utente C++


Stringhe di input dell'utente

È possibile utilizzare l'operatore di estrazione >>su cinper visualizzare una stringa inserita da un utente:

Esempio

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

Tuttavia, cinconsidera uno spazio (spazio bianco, tabulazioni, ecc.) come carattere di chiusura, il che significa che può visualizzare solo una singola parola (anche se si digitano più parole):

Esempio

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

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

Dall'esempio sopra, ti aspetteresti che il programma stampi "John Doe", ma stampa solo "John".

Ecco perché, quando si lavora con le stringhe, utilizziamo spesso la getline() funzione per leggere una riga di testo. Prende cincome primo parametro e la variabile stringa come seconda:

Esempio

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