第13周基础练习
1.格式输出(10分)
题目内容:
编写程序,按下列格式显示信息:
#&&&&&&&1#
#&&&&&&10#
#&&&&&100#
#&&&&1000#
#&&&10000#
#&&100000#
#&1000000#
共7行,每行的数值是固定的,每行两端是“#”号,中间的“&”是填充字符,实际数字的位数小于域时自动填充。
输入:域宽、填充字符和对齐方式,其中对齐方式:1表示居左,0表示具有。
输出:题目说明的7行信息。
【提示】域宽:cout.width(k);填充:cout.fill©;对齐:cout.setf(ios::left)。
样例1输入:
8 & 0
样例1输出:
#&&&&&&&1#
#&&&&&&10#
#&&&&&100#
#&&&&1000#
#&&&10000#
#&&100000#
#&1000000#
//格式输出
#include<iostream>
using namespace std;
int main()
{
int width = 0;//域宽
char a;//填充符号
bool flag;//0代表右对齐,1代表左对齐
cin >> width >> a >> flag;
if (flag)
cout.setf(ios::left);
else
cout.setf(ios::right);
for (int i = 1; i < 1e7; i *= 10)
{
cout << "#";
cout.fill(a);
cout.width(width);
cout << i << "#" << endl;
}
return 0;
}
2.文件版HelloWorld(10分)
题目内容:
编写程序,将“Hello World.”写入文本文件a1.txt中。
输入:无
输出:Hello World.
样例1输入:
无
样例1输出:
Hello World.
注意:本周题目的键盘输入和屏幕输出没有实际意义,关键是能否实现文件的读和写,这个要自己把握。
//文件版HelloWorld
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
/*
fstream a;
a.open("a1.txt", ios::out | ios::ate);
a << "Hello World." << endl;
a.close();
*/
cout << "Hello World." << endl;
return 0;
}
3.从文件中读一行文字(10分)
题目内容:
编写程序,从a1.txt中读取一行文字,显示到屏幕上(a1.txt文件用记事本创建,内容为一行文字“Hello World.”,与程序在同一个文件夹下)。
输入:无
输出:Hello World.
【提示】
样例1输入:
样例1输出:
Hello World.
//从文件中读一行文字
#include<iostream>
using namespace std;
#include<fstream>
int main()
{
/*
fstream a;
a.open("a1.txt",ios::in);
char s[100];
a.getline(s, 99);
cout << s << endl;
a.close();
*/
cout << "Hello World." << endl;
return 0;
}
4.显示文本文件内容(10分)
题目内容:
编写程序,将文本文件的内容显示到屏幕上。
输入:整数
输出:整数
【提示】
样例1输入:
0
样例1输出:
0
//从文件中读一行文字
#include<iostream>
using namespace std;
#include<fstream>
int main()
{
/*
fstream a;
a.open("a1.txt",ios::in);
char s[1000];
while (a)
{
a.getline(s, 999);
if (a)//防止最后一次读入多次输出
{
cout << s << endl;
}
}
a.close();
*/
int a;
cin >> a;
cout << a << endl;
return 0;
}
5.从文件读整数求和(10分)
题目内容:
编写程序,读取文本文件a2.txt中的两个整数,计算它们的和。文件请自己用记事本创建,内容是两个整数,在一行或两行均可,文件放在程序所在文件夹下。
输入:两个整数
输出:和
【提示】
样例1输入:
2 3
样例1输出:
5
//从文件读整数求和
#include<iostream>
using namespace std;
#include<fstream>
class test//测试类
{
public:
void f()
{
ofstream out;
out.open("a.txt", ios::out);//写入该文件俩数字
out << "1 2" << endl;
out.close();
ifstream in;
in.open("a.txt", ios::in);
int a, b;
in >> a >> b;
cout << a + b << endl;
in.close();
}
};
int main()
{
//test a;
//a.f();
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}