计算机程序设计C++ MOOC
测试与作业C++基础练习100题
##第十三周基本练习
本周内容C++中格式输出以及文件读写
- 格式输出
#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;
}
- 文件版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;
}
- 从文件中读一行文字
#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;
}
- 显示文本文件内容
本题应该无输入,从文件读取,将文件的内容全部输出到屏幕
#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;
}
- 从文件读整数求和
此例中输入应是文本文件中的数据
#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;
}
以上为第十三周的基本练习。