您的位置:首页 > 编程语言 > C语言/C++

C++错误输入后程序执行步骤

2016-06-16 22:02 387 查看

Stream Fail State

When a stream enters the fail state, further I/O operations using that stream have no effect at all. But the computer does not automatically halt the program or give any error message

当流输入进一个错误的数据,所有之后的数据都不会得到使用,但计算机不会自动停下程序或者给出错误信息

possible reasons for entering fail state include:

1、invalid input data (often the wrong type)

错误数据输入

2、 opening an input file that doesn’t exist

打开了一个不存在的输入文件

3、opening an output file on a diskette that is already full or is write-protected

打开了一个输出受限的文件

例:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
int i, j, k;
i = 10;
j = 20;
cin >> i >> j >> k;
cout << "i: " << i << endl;
cout << "j: " << j << endl;
k = 30;
cout << "k: " << k << endl;
cin.clear();    //  清楚错误状态
cin.ignore();   //  忽略这个‘/’符号
cin >> k;
cout << "k: " << k << endl;
}


input:

100 213/3123132

output:

i: 100

j: 213

k: 30

k: 3123132

关于cin.ignore()用法

The ignore( ) function is used to skip (read and discard) characters in the input stream. The call

cin.ignore ( howMany, whatChar ) ;


will skip over up to howMany characters or until whatChar has been read, whichever comes first.

cin.ignore(a,ch)方法是从输入流(cin)中提取字符,提取的字符被忽略(ignore),不被使用。每抛弃一个字符,它都要计数和比较字符:如果计数值达到a或者被抛弃的字符是ch,则cin.ignore()函数执行终止;否则,它继续等待。它的一个常用功能就是用来清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的影响。比如可以这么用:cin.ignore(1024,’\n’),通常把第一个参数设置得足够大,这样实际上总是只有第二个参数’\n’起作用,所以这一句就是把回车(包括回车)之前的所以字符从输入缓冲(流)中清除出去。

例:

#include <iostream>
using namespace std;
void main()
{
int a,b,c;
cout<<"input a:";
cin>>a;
cin.ignore(1024, '\n');
cout<<"input b:";
cin>>b;
cin.ignore(1024, '\n');
cout<<"input c:";
cin>>c;
cout<<a<<"\t"<<b<<"\t"<<c<<endl;
}


如果没有cin.ignore(),可以一次输入3个数,用空格隔开就好了。。可是非常不美观。。这样才是我们想要的。

如果cin.ignore()不给参数,则默认参数为cin.ignore(1,EOF),即把EOF前的1个字符清掉,没有遇到EOF就清掉一个字符然后结束,会导致不正确的结果,因为EOF是文件结束标识呵。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 io