简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM