fqy131314

项目2(文件流)

输入任意多个整数, 把这些数据保存到文件data.txt中.

如果在输入的过程中, 输入错误, 则提示用户重新输入.

指导用户输入结束(按ctrl + z)

[每行最多保存10个整数]

cin.ignore(count, c);

从输入流中提取并丢弃字符,直到遇到下列三种情况

1.提取的字符达到了参数count指定的数量

2.在输入序列中遇到文件结束(EOF)

3.输入序列中的下一个字符为参数c指定的字符(这个字符会被提取并丢弃)

count常常取:

std::numeric_limits<std::streamsize>::max()  相当于IO流的最大字符个数

常见用法:(把标准输入缓冲区cin的所有数据都清空)

cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

提示:这个不能和#include <Windows.h>一起使用

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
	int num;
	int n = 0;
	ofstream stream;
	stream.open("num.txt");
	if (!stream.is_open())
	{
		cout << "文件打开失败" << endl;
		exit(1);
	}
	
	while (1)
	{
		//输入一个整数
		cout << "请输入一个整数:";
		cin >> num;

		if (cin.eof())
		{
			break;
		}

		//把标准输入缓冲区cin的所有数据都清空(标准输入缓冲区以回车结束)
		// cin.ignore(std:: numeric_limits<streamsize>::max(),'\n');
		

		//如果输入错误,需要反复重复输入
		while (cin.fail())
		{
			cin.clear();
			//cin.sync();在vs中无效
			//把cin的输入缓冲区中的数据全部清除,知道遇到回车符
			cin.ignore(std::numeric_limits<streamsize>::max(), '\n');//10表示最多扔掉的数据,1表示遇到1不扔,否则把数据扔掉
			cout << "输入错误,请重新输入:";
			cin >> num;
		}

		stream << num << "\t";
		if (++n % 10 == 0)
		{
			stream << endl;
		}
	}

	stream.close();

	system("pause");
	return 0;
}

posted on   会飞的鱼-blog  阅读(8)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示