输入未清除
问题描述:
正如问题所述,出于某种原因,我的程序并未以目前无法识别的方式刷新输入或使用变量。这是一门功课的项目,我已经超过了我为它做,现在我只想程序实际工作:P输入未清除
细节,使查找更容易:
程序执行完美无缺在第一次通过。所有抛出工作,只有适当的值(n> 0)被接受并变成二进制。
只要输入我的终止输入,程序进入一个循环,并只要求等,从而再次终止:
当我在我的Linux笔记本电脑上运行Netbeans的这个程序,我输入终止值后程序崩溃。在Windows上的Visual C++中,它像上面描述的那样进入循环。
在代码中,我尝试清除每个流,并在程序重新启动时初始化每个变量,但无济于事。我只是看不到我的错误。
我相信躺在无论是在主函数的错误:
int main(void)
{
vector<int> store;
int terminate = 1;
do
{
int num = 0;
string input = "";
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Please enter a natural number." << endl;
readLine(input, num);
cout << "\nThank you. Number is being processed..." << endl;
workNum(num, store);
line;
cout << "Go again? 0 to terminate." << endl;
cin >> terminate // No checking yet, just want it to work!
cin.clear();
}while(terminate);
cin.get();
return 0;
}
或在读取号码的功能:
void readLine(string &input, int &num)
{
int buf = 1;
stringstream ss;
vec_sz size;
if(ss.fail())
{
ss.clear();
ss.ignore(numeric_limits<streamsize>::max(), '\n');
}
if(getline(cin, input))
{
size = input.size();
for(int loop = 0; loop < size; ++loop)
if(isalpha(input[loop]))
throw domain_error("Invalid Input.");
ss << input;
ss >> buf;
if(buf <= 0)
throw domain_error("Invalid Input.");
num = buf;
ss.clear();
}
}
答
当你调用cin >> terminate
,它会读取的值终止,但在输入流中保留下一个换行符。当你打电话给getline(cin, input)
时,它会读到换行符,这意味着它会得到一个空字符串。
您可以通过cin >> terminate
后添加此放弃所有字符,直到达到新行:
cin.ignore(99, '\n');
或避免混合operator >>
和getline
。
答
不要混合那些>>
和getline
运营商作为interjay提到。 另外,如果你想清楚你的代码,我认为它可以改写的folllowing方式:
int main() {
while (true) {
std::cout << "Please enter a natural number" << std::endl;
int num;
std::cin >> num;
// Exception handling here can be done easily
// like this
// if (!(std::cin >> num) || num < 0)
// throw std::domain_error("TROLOLOLO");
std::cout << "Thank you. Number is being processed..." << std::endl;
//workNum(num, store) here
std::cout << "Go again? 0 to terminate." << std::endl;
int terminate;
std::cin >> terminate;
if (terminate == 0) break;
}
}
AAAAH,我认为如果(cin.fail())将清除流,但是啊,这是一个逻辑错误^^谢谢! – IAE 2010-04-25 12:42:30