C++ Streams
来源:互联网 发布:神界原罪2低配优化 编辑:程序博客网 时间:2024/06/14 00:49
1.fstream
File: table-data.txt 的内容为
137 2.71828
42 3.14159
7897987 1.608
1337 .01101010001
从上述文件中读取第一个整数和第二个小数。
ifstream inFile("table-data.txt");if (!inFile.is_open())cerr << "couldn't open the file";while (true){int intValue;double doubleValue;inFile >> intValue >> doubleValue;if (inFile.fail()){break;}cout << intValue << " | ";cout << doubleValue;cout << endl;}
当文件第一列不再是整数,而是字符串时,流进入error state,fail会被置成true,从而该程序中的while循环结束。
当文件第一列不再是整数,而是小数时,intValue会读取小数点前的部分,doubleValue会读取小数的小数点后的部分。此时fail不为true。
如果小数点前没有整数,如intValue读取的是 0.123,fail置为true。
2.iostream
假设要求用户从控制台输入密码和对格式化磁盘的确认选项,示例如下:
string password;cout << "Enter administrator password: ";cin >> password;if (password == "password"){cout << "Do you want to erase your hard drive (Y or N) ?" << endl;char yesOrNo;cin >> yesOrNo;if (yesOrNo == 'y'){cout << "Erase!" << endl;}}如果用户按照如下格式输入:
输入“password”后,回车,输入’Y‘后,回车。程序正确运行。
如果用户按照如下格式输入:
输入“password”后,键入若干个空格,键入“yyyyy”,回车,程序执行格式化!
因此,直接使用cin来读取数据是不安全的,并且可以产生很多不能解决的问题!
阅读全文
0 0
- STREAMS
- Streams
- Streams
- Streams
- 【精华】关于C中的输入输出缓冲-buffering in standard streams
- c2 Streams - Output Streams
- c2 Streams - Filter Streams
- Byte Streams & Character Streams
- Output Streams
- Filter Streams
- Filter Streams
- TCPL_21 streams
- Streams errors
- streams概述
- Oracle Streams
- Streams概述
- Byte Streams
- Character Streams
- linux环境变量 export命令详解
- Android Activity
- 【JVM】Java-JVM-OutOfMemoryError实战
- CentOS 6.5_x64安装Oracle 11g R2
- Java多线程基础
- C++ Streams
- mysql导入大量数据时报MySQL server has gone away错误的解决办法
- ArrayList源码学习
- 【Data_Structure笔记7】排序算法之【链式基数排序】
- SpringBoot01
- postgresql基础配置
- string,stringbuffer,stringbuilder的区别
- LinkedList源码学习
- java总结输入流输出流