I am writing a program in C++ which is supposed to take an input string from user, print it and ask the user to type in another string again and print it again until the user presses the return key without typing any string. In that case the program should exit.
I came up with the following, but it doesn't work as desired. Any ideas?
int main(){
string surname;
int c;
while (true) {
surname = "";
cout << "Enter surname (RETURN to quit): ";
c = cin.get();
if (c == '\n') {
break;
}
cin >> surname;
cout << surname << endl;
}
return 0;
}
You don't need to initialize std::string like this: string surname; surname = ""; It's not necessary.
You could use getline function and then check if this string is empty like this:
string surname;
cout << "Enter surname (RETURN to quit): ";
while (getline(cin, surname))
{
if (surname.empty())
break;
cout << surname << endl << "Enter surname (RETURN to quit): ";
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With