2013-06-28 168 views
1

所以我试图做一个只接受整数的循环,它起初工作正常,但只要不是整数的东西被输入串流,它将不断跳过如果声明即使使用了正确的输入。我错过了什么吗?检查输入是否是整数循环

# 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(""); 
} 

} 

回答

0

移动ss.str("");for循环中,让你读下一行之前的stringstream将被清除。

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

或者,你可以使用:

ss.str(str); 

填补了stringstream从输入,而不是追加到它与>>

+0

oops额外{来自复制/粘贴错误。我在for循环中移动了ss.str(“”),但我仍然遇到同样的问题。 – user2533259

相关问题