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 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- C语言练习题:自由落体的小球简单实例
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中进制知识汇总
- C语言判断一个数是否是2的幂次方或4的幂次方
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- C语言实现选择排序、冒泡排序和快速排序的代码示例