终止与空白

时间:2014-01-18 03:04:01

标签: c++

而不是像这样编写代码

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

无论有多少个空格,我如何让用户终止程序?

2 个答案:

答案 0 :(得分:1)

创建自己的空间函数:

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

然后像这样使用它:

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

答案 1 :(得分:1)

只需使用

while (getline(cin, inputWord))
{
    if(inputWord.find_first_not_of(' ') == std::string::npos) // all spaces
        return 0;
}
相关问题