【问题标题】:checking if an input is an integer loop检查输入是否为整数循环
【发布时间】:2013-06-28 20:34:26
【问题描述】:

所以我正在尝试创建一个只接受整数的循环,它最初工作正常,但是一旦输入不是整数的东西,即使输入正确,它也会不断跳过 if 语句用过的。我错过了什么吗?

# include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;


int main()
{
  string str;
  stringstream ss;
  int a;


  for(;;)
    {
      getline(cin, str);
      ss<<str;
      if (ss>> a)
        {
          cout<<"okay";
          break;
        }
      cout<<str<<endl;//debugging (prints the correct input
      str.clear();    //
      ss>>str;        //
      cout<<str<<endl;// doesn't print anything but the endl space
      cout<< "try again";
ss.str("");
}

}

【问题讨论】:

    标签: loops if-statement input int stringstream


    【解决方案1】:

    ss.str(""); 移动到for 循环内,这样stringstream 将在您阅读下一行之前被清除。

    您粘贴的代码中还有一个额外的}。也许这与那条线如何在循环之外结束有关。

    或者,您可以使用:

    ss.str(str);
    

    从输入中填写stringstream,而不是附加到&gt;&gt;

    【讨论】:

    • 哎呀,额外的 { 来自复制/粘贴错误。我在 for 循环中移动了 ss.str("") 但我仍然遇到同样的问题。
    猜你喜欢
    • 2022-06-17
    • 2016-05-19
    • 2013-03-13
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多