输入任意多个整数, 把这些数据保存到文件data.txt中.
如果在输入的过程中, 输入错误, 则提示用户重新输入.
指导用户输入结束(按ctrl + z)
[每行最多保存10个整数]
#include<iostream>
#include<fstream>
using namespace std;
int main() {
int count = 1;
int num;
ofstream stream;
stream.open("num.txt");
if (!stream.is_open()) {
cout << "文件打开失败" << endl;
exit(1);
}
while (1) {
cout << "请输入第" << count << "个数据(ctrl+Z结束)" << endl;
cin >> num;
if (cin.eof()) {
break;
}
while (cin.fail()) {
cin.clear(); //清除错误标志
//cin.sync(); 在vs中无效
// 把cin的输入缓冲区中的数据全部清除,直到遇到回车符
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
cout << "输入错误,请重新输入:";
cin >> num;
}
stream << num<<"\t";
count++;
if (num % 10 == 0) {
stream << endl;
}
}
stream.close();
return 0;
}
cin.ignore(count, c);
从输入流中提取并丢弃字符,直到遇到下列三种情况
1.提取的字符达到了参数count指定的数量
2.在输入序列中遇到文件结束(EOF)
3.输入序列中的下一个字符为参数c指定的字符(这个字符会被提取并丢弃)
count常常取:
std::numeric_limitsstd::streamsize::max() 相当于IO流的最大字符个数
常见用法:(把标准输入缓冲区cin的所有数据都清空)
cin.ignore(std::numeric_limits::max(), ‘\n’);