ReeSSult
ReeSSult

Reputation: 496

Check if user input a blank c++

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?

Upvotes: 0

Views: 2522

Answers (1)

R Sahu
R Sahu

Reputation: 206567

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;
   }
}

Upvotes: 2

Related Questions