Stringhe di input utente C++
Stringhe di input dell'utente
È possibile utilizzare l'operatore di estrazione >>
su cin
per 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, cin
considera 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 cin
come 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