Reputation: 2176
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;
}
Upvotes: 3
Views: 21209
Reputation: 75150
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 string
variable. Also, you need to use std::getline(std::cin, stringvariable)
instead of cin >> stringvariable
because 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 calling empty
on it.
Upvotes: 2
Reputation: 43284
The problem is that when asking for a string, the iostream library will always return a single word, ignoring any spaces. This is very useful in most situation. But if you want to detect an empty string, you should read a character, and check if it's a new line character first:
while(true) {
char c;
string surname;
cout << "Enter surname (RETURN to quit): ";
cin.get(c)
if(c == '\n') break;
cin >> surname;
if(c != ' ' and c != '\t' and c != '\n')
surname.insert(0, c);
}
return 0;
Note that this solution has a few problems if the name is one character long. You might need to just use cin.get
to obtain the whole string ...
Upvotes: 2
Reputation: 42103
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.
Upvotes: 5
Reputation: 993901
I don't recommend using cin >>
for an interactive program. Its behaviour is well-defined, but often unexpected for user-typed input. Instead, use something like:
std::getline(std::cin, surname);
This will always wait until the user types a bunch of stuff and presses Enter, without odd behaviours like buffering data in the stream for later.
Upvotes: 2