0

I need to make a loop that gets three strings as input from a user and stop if nothing is entered. My code

while(true){ cout << "Enter string1 string2 string3: "; getline(cin,s1, ' '); if(s1.empty()) break; getline(cin, s2, ' '); getline(cin, s3); } 

If I don't enter anything, getline waits until I input at least a space. How to make it stop when nothing is entered?

2

1 Answer 1

2

My suggestion:

  1. Read a line of text.
  2. Use the line to construct a istringstream. Use the istringstream to extract the variables.

Here's what I am thinking:

std::string line; while ( getline(std::cin, line) ) { std::istringstream str(line); if ( !(str >> s1 >> s2 >> s3 ) ) { break; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, had the same idea, didn't know how to implement in right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.