1. 程式人生 > >實驗7流類庫和輸入輸出

實驗7流類庫和輸入輸出

解決辦法 9.png oom In 長度 AI 對齊 行數 gin

基礎練習:

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::adjustfield);//取消之前調用setf()的效果 cout.precision(2); cout.setf(ios_base::uppercase | ios_base::scientific);//使用科學技術法輸出,且對於16進制輸出時,使用大寫字母,E表示。 cout << 831.0; cout.flags(original_flags);//恢復初始參數 return 0; }

11-3-4:

源代碼:

#include<iostream>
#include
<fstream> #include<string> using namespace std; int main(){ ofstream os("test1.txt"); if (os) { os << "已成功寫入文件!"; } os.close(); ifstream is("test1.txt"); if (is) { string s1; getline(is, s1); cout << s1; } is.close();
return 0; }

運行效果:

技術分享圖片

技術分享圖片

應用練習:

(1)

源代碼:

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<ctime>
using namespace std;
struct stu {
    int num;
    string num2, name, room;
}student[100];
int main() {
    ifstream is("list.txt");
    if (!is) {
        cout << "ERROR" << endl;
        return 1;
    }
    int i = 0;
    while (is >> student[i].num >> student[i].num2 >> student[i].name >> student[i].room) {
        i++;
    }
    is.close();
    ofstream os("roll.txt");
    srand((unsigned)time(NULL));
    for (int i = 0; i < 5; i++) {
        int m = (rand() % 83);
        cout << student[m].num << " " << student[m].num2 << " " << student[m].name << " " << student[m].room << endl;
        os << student[m].num << " " << student[m].num2 << " " << student[m].name << " " << student[m].room << endl;
    }
    os.close();
    return 0;
}

運行效果:

技術分享圖片

技術分享圖片

(2)用getline()函數得出行數line;對每行用getline()得到的字符串s1測長度,即s1.size(),然後將每行的s1長度都加起來,得到字符數;求單詞數則可以對每行的字符逐個檢查,如果是字母且後一個字符為空格或標點符號,則是單詞,將每行的單詞數相加,即可得到單詞總數。

源代碼:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
    ifstream is("article.txt");
    int line = 0; int num1 = 0; int word = 0;
    if (is) {
        string s1; int m;
        while (getline(is, s1)) {
            m = s1.size();
            line++;
            num1 = num1 + m;
            for (int i = 0; i < m; i++) {
                if (s1[i] >= A&&s1[i] <= Z || s1[i] >= a&&s1[i] <= z) {
                    if (s1[i + 1] >= !&&s1[i + 1] <= /||s1[i+1]== ||s1[i+1]>=:&&s1[i+1]<=?) {
                        word++;
                    }
                }
            }
        }
    }
    is.close();
    cout <<"行數為:"<< line << " 字符數為:" << num1 <<" 單詞數為:"<<word<< endl;
    return 0;
}

運行效果:

技術分享圖片

文件:

技術分享圖片

總結與體會:

此次實驗是目前為止我感覺最為棘手的一次,困擾了整整一天。可能是因為以前沒怎麽接觸過吧,剛開始感覺一籌莫展。我在應用練習的第一題花了大量時間,一開始無論如何都無法輸入;我研究了一整個下午,沒辦法去參考別的同學的答案,換了四五種,卻毫無進展;當我最後解決了問題之後,反而忘了最初自己的想法,實在是悲哀。在此我要感謝“MINt超”同學,我看到了他對另一個同學的評論後找到了解決辦法,即自己新建一個list.txt,不直接用附件裏的list,雖然現在仍不知道為何會出問題。而出了這麽一檔子事之後對於實驗的選做部分我也實在是有心無力了,或許以後能力足夠了會回來完善……

實驗7流類庫和輸入輸出