20200105 控制台环境下,文件的写入和错误时清空缓存、错误标志

#include <Windows.h>
#include<iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
	string name;
	int age;
	char c;
	ofstream file;
	file.open("user.txt");
	if (file.fail()) {
		cout << "打开文件失败";
		exit(1);
	}
	while (1) {
		cout << "请输入名字[ctrl+z退出]:";
		cin >> name;	
		if (cin.eof()) {
			break;
		}
		cout << "请输入年龄:";
		cin >> age;
		if (cin.fail()) {	
			cout << "输入错误!" << endl;
			cin.clear();//清除错误标志
			//fflush(stdin);
			while (( c=getchar())!='\n');//清除缓存,还可以一起清空name的输入
		}
		else {
			file << name << "\t" << age<<endl;
			//file << age << endl;
		}
		
	}
	file.close();

	system("pause");
	return 0;
}
发布了48 篇原创文章 · 获赞 0 · 访问量 371

猜你喜欢

转载自blog.csdn.net/weixin_40071289/article/details/103846641
今日推荐