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来读取数据是不安全的,并且可以产生很多不能解决的问题!

原创粉丝点击