C++ 如何在从输入流读取数据时清除故障位?
我试图从输入流中读取整数,当它读取字符(输入的一部分)时,failbit被设置,它停止读取流,我想清除failbit并读取到下一个输入整数。我应该做哪些更改以获得正确的输出C++ 如何在从输入流读取数据时清除故障位?,c++,C++,我试图从输入流中读取整数,当它读取字符(输入的一部分)时,failbit被设置,它停止读取流,我想清除failbit并读取到下一个输入整数。我应该做哪些更改以获得正确的输出 int main() { int x; while(cin >> x) { if(cin.fail()) cin.clear(); cout << x; } } intmain() { int x; 而(cin>>x) {
int main()
{
int x;
while(cin >> x)
{
if(cin.fail())
cin.clear();
cout << x;
}
}
intmain()
{
int x;
而(cin>>x)
{
if(cin.fail())
cin.clear();
cout当发现无效字符时,while循环中的条件将失败。您还需要使用无效字符,否则下一次提取操作将再次失败:
int main()
{
int x;
while(true)
{
cin >> x;
if(cin.eof())
{
break;
}
if(!cin)
{
cin.clear();
//consume the invalid character
cin.ignore();
continue;
}
cout << x;
}
}
intmain()
{
int x;
while(true)
{
cin>>x;
if(cin.eof())
{
打破
}
如果(!cin)
{
cin.clear();
//使用无效字符
cin.ignore();
继续;
}
cout您遇到的问题是在检查fail
之前没有检查eofbit
是否已设置。您需要在测试fail
和清除流状态之前退出EOF
上的读取循环,例如
#include <iostream>
int main (void) {
int x = 0;
while (1) /* loop continually reading input */
{
if (! (std::cin >> x) ) { /* check stream state */
/* if eof() or bad() break read loop */
if (std::cin.eof() || std::cin.bad())
break;
else if (std::cin.fail()) { /* if failbit */
std::cin.clear(); /* clear failbit */
x = std::cin.get(); /* consume next char */
}
}
else /* on succesful read, just output int */
std::cout << x;
}
std::cout << '\n'; /* tidy up with newline */
}
如果您想直接检查failbit
,则使用rdstate()
。在这种情况下,您可以确认failbit
排除在badbit
之外,然后使用clear()
,例如
if (! (std::cin >> x) ) { /* check stream state */
if (std::cin.rdstate() == std::ios_base::failbit) {
std::cin.clear(); /* if failbit */
x = std::cin.get(); /* consume next char */
}
else /* else if eofbit or badbit - break read loop */
break;
}
else /* on succesful read, just output int */
std::cout << x;
if(!(std::cin>>x)){/*检查流状态*/
if(std::cin.rdstate()==std::ios_base::failbit){
std::cin.clear();/*如果失败位*/
x=std::cin.get();/*使用下一个字符*/
}
else/*else如果是eofbit或badbit-中断读取循环*/
打破
}
else/*在成功读取时,只输出int*/
std::cout无效字符
,例如不是整数的what?@EJP字符,如OP问题中的“a”
if (! (std::cin >> x) ) { /* check stream state */
if (std::cin.rdstate() == std::ios_base::failbit) {
std::cin.clear(); /* if failbit */
x = std::cin.get(); /* consume next char */
}
else /* else if eofbit or badbit - break read loop */
break;
}
else /* on succesful read, just output int */
std::cout << x;