计算机程序设计C++(第13周基础练习)

计算机程序设计C++ MOOC

测试与作业C++基础练习100题

##第十三周基本练习

本周内容C++中格式输出以及文件读写

  1. 格式输出
    在这里插入图片描述
#include <iostream>

using namespace std;

int main()
{
	int width, way,n=1;
	char a;
	cin >> width >> a >> way;
	if (way == 1)
		cout.setf(ios::left);
	else
		cout.setf(ios::right);
	for (int i = 0; i < 7; i++)
	{
		cout << '#';
		cout.width(width);
		cout.fill(a);
		cout <<  n << '#' << endl;
		n *= 10;
	}
	return 0;
}
  1. 文件版HelloWorld
    在这里插入图片描述
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ofstream out("test.txt");
	if (!out)
	{
		cout << "文件打开失败" << endl;
		return 1;
	}
	out << "Hello World." << endl;
	out.close();
	cout << "Hello World." << endl;
	return 0;
}
  1. 从文件中读一行文字
    在这里插入图片描述
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream in("a1.txt");
	if (!in)
	{
		cout << "打开文件失败";
		return 0;
	}
	char a[20];
	in.getline(a, 20);
	cout << a << endl;
	return 0;
}
  1. 显示文本文件内容
    在这里插入图片描述

本题应该无输入,从文件读取,将文件的内容全部输出到屏幕

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream in("A.txt");
	if (!in)
	{
		cout << "打开文件失败";
		return 0;
	}
	char a[802];
	while (in)
	{
		in.getline(a, 800);
		if (in)
			cout << a << endl;
	}
	in.close();
	return 0;
}
  1. 从文件读整数求和
    在这里插入图片描述

此例中输入应是文本文件中的数据

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	int a[2], i = 0,n = 0,sum = 0;
	ifstream in("A.txt");
	if (!in)
	{
		cout << "打开文件失败";
		return 0;
	}	
	while (in)
	{
		in >> a[i];	
		i++;
		n++;
	}	
	n--;
	in.close();
	for (int i = 0; i < n; i++)
	{
		sum += a[i];
	}
	cout << sum << endl;
	return 0;
}


以上为第十三周的基本练习。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值