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;
}
I will give you some tips so that I don’t solve the problem for you, but help you along.
You don’t need to read one character at a time, you can read each line into a
stringvariable. Also, you need to usestd::getline(std::cin, stringvariable)instead ofcin >> stringvariablebecause the latter will skip all newlines until it gets to a non-newline character, so pressing enter by itself will not do anything.After using
std::getline, you can tell if the user entered anything by comparing the length of the string with 0 or callingemptyon it.