所以我试图创建一个只接受整数的循环,它最初工作正常,但是一旦输入不是整数的东西,即使使用了正确的输入,它也会不断地跳过 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("");
}
}