基礎練習:ios
(1)教材習題11-7函數
#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::uppercase|ios_base::scientific); //改爲浮點數的顯示設置 cout << 831.0; cout.flags(original_flags); //恢復保存的格式化參數設置 return 0; }
(2)教材習題11-3spa
#include<iostream> #include<fstream> using namespace std; int main(){ ofstream filel("test.txt"); filel << "已成功寫入文件!"; filel.close(); return 0; }
(3)教材習題11-43d
#include<iostream> #include<fstream> using namespace std; int main(){ char s; ifstream in ("test.txt"); if (!in) { cout << "fail to open." << endl; return 1; } in >> s; cout << s << endl; in.close() ; return 0; }
應用練習:code
(1)blog
#include<iostream> #include<fstream> #include<string> #include<stdlib.h> #include<ctime> using namespace std; struct student { int num; string ID; string name; string clas; }stu[100]; int main(){ ifstream in ("list.txt"); if (!in){ cout << "fail to open." << endl; return 1; } int i = 0; while (in >> stu[i].num >> stu[i].ID >> stu[i].name >> stu[i].clas) i++; //統計有幾位同窗 in.close (); ofstream out ("roll.txt"); //存放被點的人 srand((unsigned)time(NULL)); //利用時間隨機 for ( int n = 1; n <= 5; n++ ) //隨機五位 { int a = 1 + rand() % ( i + 1 ) ; cout <<stu[a].num << " " <<stu[a].ID << " " <<stu[a].name << " " <<stu[a].clas << endl; out <<stu[a].num << " " <<stu[a].ID << " " <<stu[a].name << " " <<stu[a].clas << endl; } out.close(); return 0; }
不知道爲何輸出的全是0……看了看好像好幾個同窗都這樣啊…求大佬解釋……ci
(2)string
#include<iostream> #include<fstream> using namespace std; bool str(char a){ //判斷是不是字符 if((a>='A'&&a<='z')||(a>='0'&&a<='9')) return true; else return false; } int main(){ int str_number = 0; //統計字符數 int word_number = 0; //統計單詞數 int line_number = 1; //統計行數 ifstream in("data.txt"); if(!in){ cout << "fail to open." << endl; return 1; } while(in){ char a; in.read(reinterpret_cast<char*>(&a),sizeof(a)); if(str(a)) str_number++; if(a==' '||a=='.'||a==','||a=='!'||a=='?'||a=='"'||a=='('||a==')'||a==':') word_number++; if(a=='\n') line_number++; } in.close(); cout << "字符數:" << str_number << endl; cout << "單詞數:" << word_number << endl; cout << "行數:" << line_number << endl; return 0; }
思路:io
字符數:用一個bool類型函數判斷是不是字符。ast
單詞數:我是用統計標點符號和空格的數目來間接統計單詞數,可是我有個疑問,若是一個單詞後面跟着兩個或以上標點好比說「Then...」,這樣就不許了,不知道怎麼解決。
行數:統計換行符的個數。