gpt4 book ai didi

c++ - 如何正确使用 cin.clear 和 cin.ignore

转载 作者:行者123 更新时间:2023-11-30 04:56:53 36 4
gpt4 key购买 nike

    int main()
{
int oddeven = 1;
int modulotwo;
// Simple loop since no reason to check 0
while(oddeven != 0){
//user input
cout << "\n\nIn while loop\n";
cout << "Input number to determine if it is odd or even.\n";
cin >> oddeven;
//check to see if input succesful
if(!(cin.fail())) {
cout << "In if loop\n";
cout << "Divide by two and put in modulotwo.\n";
//check to see if odd or even by dividing by 2
modulotwo = oddeven % 2;
cout << "Output modulotwo: ";
//visual confirmation of remainder
cout << modulotwo << "\n";
if (modulotwo == 0) {
cout << "Check modulotwo against 0\n";
cout << "The number " << oddeven << " is even.\n";

}
else {
cout << "The number " << oddeven << " is odd.\n";

}
}
//If input not succesful
else {
cout << "In else statement. Set oddeven to 1\n";
//set oddeven to 1 to stop exit
oddeven = 1;
cout << "Not a usable number, please input integer number." << endl;
cout << "Run cin.clear\n";
cin.clear();
cout << "Run cin.ignore\n";
cin.ignore(std::numeric_limits<std::streamsize>::max());

}
}

}

我在上面有一个“简单”的代码来检查数字是奇数还是偶数。我正在尝试向其添加纠错以确保输入的类型正确。我被指向 cin.clear 和 cin.ignore。我的问题是,如果我导致错误,它会正确地放入 else 语句中,仅此而已。它将不再运行其余部分。我假设它来自 cin.ignore。如何让它正确清除错误并返回输入循环?如果我删除 cin.ignore,我会得到一个连续的循环,告诉我 1 是奇数,而无需等待任何输入。

额外的输出文本是我尝试跟踪代码的位置和作用的方式。

编辑。在发帖之前,我实际上已经将 cin.ignore 注释掉了。我试图自己研究这个问题并且遇到了关于它寻找换行符的评论,但正如你们都发现的那样,它不起作用。输入字母而不是任何数字时会出现问题,无论是太大还是其他。

最佳答案

My issue is, if I cause an error it correctly drops into the else statement, but that is it. It will no longer run the rest.

问题出在线路上

cin.ignore(std::numeric_limits<std::streamsize>::max(), "\n");

第二个参数需要是一个字符,而不是一个字符串。

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

提高编译器的警告级别以检测此类错误。

通过使用 g++ -std=c++11 -Wall,我收到以下警告/错误消息。

socc.cc: In function ‘int main()’:
socc.cc:43:70: error: invalid conversion from ‘const char*’ to ‘std::basic_istream<char>::int_type {aka int}’ [-fpermissive]
cin.ignore(std::numeric_limits<std::streamsize>::max(), "\n");
^
In file included from /usr/include/c++/5/iostream:40:0,
from socc.cc:1:
/usr/include/c++/5/istream:657:5: note: initializing argument 2 of ‘std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::ignore(std::streamsize, std::basic_istream<_CharT, _Traits>::int_type) [with _CharT = char; _Traits = std::char_traits<char>; std::streamsize = long int; std::basic_istream<_CharT, _Traits>::int_type = int]’
basic_istream<char>::

关于c++ - 如何正确使用 cin.clear 和 cin.ignore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305917/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com