0

Instead of writing code like this

while (getline(cin, inputWord))
{
   if (inputWord.empty() || inputWord == " " || inputWord == "  " || inputWord == "   ")return 0;
}

How can I get the user to terminate the program regardless of how many whitespaces are present?

Kilo King
  • 189
  • 1
  • 4
  • 14
  • Does `cin.ignore()` do it for you? See http://stackoverflow.com/questions/4876959/ignore-spaces-using-getline-in-c – kmort Jan 18 '14 at 03:07
  • 1
    possible duplicate of [Efficient way to check if std::string has only spaces](http://stackoverflow.com/questions/6444842/efficient-way-to-check-if-stdstring-has-only-spaces) –  Jan 18 '14 at 03:08
  • @Nabla I've tried that, but it doesn't work. – Kilo King Jan 18 '14 at 03:15
  • @user3200730 Then you should ask about why this answer does not work for you instead of asking nearly the same again. The answer provided there is probably correct, seeing it is highly upvoted, so probably you are doing something wrong or missed something. Please post the full code you tried. –  Jan 18 '14 at 03:17

2 Answers2

1

Make your own function that counts spaces:

int countWhiteSpaces(string input)
{
    // You do it :) Hint: a 'for' loop might do
}

And then use it like this:

while (getline(cin, inputWord))
{
   if (inputWord.empty() || countWhiteSpaces(inputWord) > 0)
      return 0;
}
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
  • It took me a few moments to catch what to do, but I pieced it together. Thank you, this was very useful :) – Kilo King Jan 18 '14 at 03:35
  • You're welcome! Just remember: when you see a problem that's too big for you to solve, try to see if there's a sub-problem that's easier to solve, and then generalize the idea. – Maria Ines Parnisari Jan 18 '14 at 03:36
1

Just use

while (getline(cin, inputWord))
{
    if(inputWord.find_first_not_of(' ') == std::string::npos) // all spaces
        return 0;
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174