问题描述:
要求把第二个文件拼接到第一个文件的末尾。 如把file2 拼接到 file末尾。 (直接复制一下不就行了嘛! 但是老师非让编程, 真是蛋疼!!,而且是闲的蛋疼!!!)。例如:
file1: I am not responsible of this code. They made me write it, against my will. file2: When I wrote this, only God and I understood what I was doing. Now, God only kowns. 拼接后: file1: I am not responsible of this code. They made me write it, against my will. When I wrote this, only God and I understood what I was doing. Now, God only kowns.
知识点: 文件流类。
#include<iostream> #include<fstream> using namespace std; const int maxn = 1000+10; int main() { char str[maxn]; ifstream cin("file2.txt"); ofstream cout("file1.txt", ios::app); while(cin.getline(str, maxn)) { cout<<str<<endl; } return 0; }
一周内请勿抄袭! 以防作业雷同!
后面的题目也是我的作业题, 也都是关于I/0流的, 只不过比较水! I/0流是理解C++面向对象的典型例子之一, 所以在此也附上。
《2》使用I/O流, 以文本方式建立一个文件。并写入一串字符。
#include<iostream> #include<fstream> using namespace std; int main() { ofstream cout("file3.txt"); cout<<"该文件已成功建立!"; return 0; }
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct stu{
string num;
string name;
double score;
}Stu; int n;
void judge(double a)
{
cout<<"成绩等级:";
if(a>=90) cout<<"优\n";
else if(a>=80) cout<<"良\n";
else if(a>=70) cout<<"中\n";
else if(a>=60) cout<<"及格\n";
else cout<<"不及格\n";
}
int main()
{
{//老是错,最后终于对啦, 原来是作用域的锅!!!
ofstream fc("stud.dat");
if(fc.fail())
{
cerr<<"error opening file\n";
return 0;
}
cout<<"请输入学生的总人数:\n";
cin>>n;
int T=n;
while(T--)
{
cout<<"请输入学生的学号 姓名 成绩\n";
cin>>Stu.num>>Stu.name>>Stu.score;
fc<<Stu.num<<" "<<Stu.name<<" "<<Stu.score<<" ";
}
}
ifstream cc("stud.dat");
while(n--)
{
cc>>Stu.num>>Stu.name>>Stu.score;
cout<<"学号:"<<Stu.num<<endl;
cout<<"姓名:"<<Stu.name<<endl;
cout<<"成绩:"<<Stu.score<<endl;
judge(Stu.score);
}
return 0;
}
《3》使用串流I/O的方式, 对字符串逐个读取。 如字符串“12345667899,,,,,”。
#include<iostream> using namespace std; int main() { char c; while(c=cin.get()) { cout<<c<<endl; } return 0; }
《4》 输入一系列的数据(学号, 姓名, 成绩)存放在文件 stud.dat中, 输出这些学生的数据和相应的成绩等级(优, 良,,,,)。
这道题有细节性问题(气死我啦!!!)。
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 6 struct stu{ 7 string num; 8 string name; 9 double score; 10 }Stu; int n; 11 12 void judge(double a) 13 { 14 cout<<"成绩等级:"; 15 if(a>=90) cout<<"优\n"; 16 else if(a>=80) cout<<"良\n"; 17 else if(a>=70) cout<<"中\n"; 18 else if(a>=60) cout<<"及格\n"; 19 else cout<<"不及格\n"; 20 } 21 int main() 22 { 23 {//老是错,最后终于对啦, 原来是作用域的锅!!! 24 ofstream fc("stud.dat"); 25 if(fc.fail()) 26 { 27 cerr<<"error opening file\n"; 28 return 0; 29 } 30 cout<<"请输入学生的总人数:\n"; 31 cin>>n; 32 int T=n; 33 while(T--) 34 { 35 cout<<"请输入学生的学号 姓名 成绩\n"; 36 cin>>Stu.num>>Stu.name>>Stu.score; 37 fc<<Stu.num<<" "<<Stu.name<<" "<<Stu.score<<" "; 38 } 39 } 40 ifstream cc("stud.dat"); 41 while(n--) 42 { 43 cc>>Stu.num>>Stu.name>>Stu.score; 44 cout<<"学号:"<<Stu.num<<endl; 45 cout<<"姓名:"<<Stu.name<<endl; 46 cout<<"成绩:"<<Stu.score<<endl; 47 judge(Stu.score); 48 } 49 return 0; 50 }