Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit program on press of return key?

Tags:

c++

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;   
}
like image 290
stressed_geek Avatar asked Jan 27 '26 12:01

stressed_geek


1 Answers

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.

like image 135
LihO Avatar answered Jan 29 '26 01:01

LihO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!