1.
(1)
#include <iostream> using namespace std; int main() { ios_base::fmtflags original_flags=cout.flags();//保存现在的格式化参数设置 cout<<812<<'|'; cout.setf(ios_base::left,ios_base::adjustfield);//把对齐方式改为左对齐 cout.width(10);//设置输出宽度为10 cout<<813<<815<<'\n'; cout.unsetf(ios_base::adjustfield);//清除之前的对齐方式设置 cout.precision(2); cout.setf(ios_base::uppercase|ios_base::scientific);//以科学形式显示浮点数值 cout<<831.0; cout.flags(original_flags);//恢复原来的格式化参数设置 return 0; }
(2)
#include <fstream> using namespace std; int main() { ofstream file("test1.txt"); file<<"已成功写入文件!"; file.close(); return 0; }
(3)
#include <fstream> #include<iostream> using namespace std; int main() { ifstream file("test1.txt"); char ch; while((ch=file.get())!=EOF) cout.put(ch); file.close(); return 0; }
2.
(1)
#include<iostream> #include<cstring> #include<fstream> #include<cstdlib> #include<ctime> using namespace std; struct student { string num; string id,name,cls; }stu[100]; int main() { ifstream fin("list.txt"); ofstream fout("roll.txt"); if(!fin) { cout<<"无法打开文件"<<endl; return 1; } int i=0; while(fin>>stu[i].num>>stu[i].id>>stu[i].name>>stu[i].cls) { i++; } int line=i;//line为txt中有多少行(空行不算),即学生的个数 int a; srand(time(NULL)); for(int i=0;i<5;i++) { a=rand()%line+1; cout<<stu[a].num<<" "<<stu[a].id<<" "<<stu[a].name<<" "<<stu[a].cls<<endl; fout<<stu[a].num<<" "<<stu[a].id<<" "<<stu[a].name<<" "<<stu[a].cls<<endl; } return 0; }
(2)
#include<iostream> #include<cstring> #include<fstream> using namespace std; int main() { ifstream fin("passage.txt"); long long line=0,word=0,ch=0;//行数,单词数,字符数 char str[10000]; int cnt=0; while(fin.getline(str,10000)) { for(int i=0;i<strlen(str);i++) { ch++; if(str[i]=='?'||str[i]==','||str[i]=='.'||str[i]=='!'||str[i]=='('||str[i]==')') word++; if(str[i]==' ') if(str[i-1]>='A'&&str[i-1]<='Z'||str[i-1]>='a'&&str[i-1]<='z') word++; } line++; } cout<<"字符数:"<<ch<<endl<<"单词数:"<<word<<endl<<"行数:"<<line; return 0; }
实验体会
通过流建立起程序和文件的联系,对流进行直接操作从而对文件进行间接操作,明白了这一点学起来就豁然开朗了。