-
<enter> to quit
Hi guys,
This may be a really dumb question but I can't seem to do this one simple thing.
I want to receive 2 strings and output stuff while the user wants me to. (I was thinking a for(;;) loop). '
For the user to quit, they need to press enter for both strings with no input.
I have read many archives, and am NOT using arrays.
When I press enter, it just goes to a new line and blinks at me, waiting for input.
Here is an example of the things I have tried:
Code:
cout << "Please enter 2 strings (just <enter> twice to quit):"
<< "\nstring 1: ";
cin >> string1;
cout << "\nstring 2:";
cin >> string2;
//here are the following things I have tried:
//firstly: (with brackets in various places!!)
if (string1.empty()&&string2.empty()) break;
//I have also tried: (with brackets in various places!!)
if (string1.size()-1=0&&string2.size()-1=0) break;
//I thought maybe?
char ch1;
cin.get(ch1);
if (ch1=='\0'&&ch2=='\o') break;
I am so frustrated. I have tried so many things and variations, but cannot seem to get it.
All I need is a simple way to do this.
Thankyou for reading this and helping (????)
s
-
cin will skip all leading whitespace (tabs, newline, spaces) and then read any characters up until the next whitespace. This means that if you run the above command, the program is going to wait forever until some non-whitespace data is encountered (skipping any and all leading newlines you enter) followed by some whitespace.
You need to use something else, like getline to read in data which will read (in its default configuration) up until the first newline encountered:
Code:
getline(cin,string1);
If you run the above command and just press the "Enter" key then string1 will contain an empty string and you can then use that "string1.empty()" command to test if nothing was entered.
-
Thankyou for your help!! I will try this now!!