【c++】輸出文件的每個單詞、行


假設文件內容為

1. hello1 hello2 hello3 hello4
2. dsfjdosi
3. skfskj  ksdfls

輸出每個單詞

代碼

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>

using namespace std;

int main()
{
    string word;
    ifstream infile("text");
    if(!infile)
    {
        cout << "cannot open the file" << endl;
        return 0;
    }
    while(infile >> word)
        cout << "word:" << word << endl;
    infile.close();
}

結果

分析

定義文件流infile,並綁定文件“text”,之后判定,如果打開錯誤,則提示錯誤,結束程序。否則,繼續執行程序:

輸入文件流infile把文件中的內容全部讀入緩沖區(文件結尾符時停止往輸入緩沖區內存),通過重定向符>>傳到word(間隔福為Tab, Space, Enter)

 

輸出每一行

代碼

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>

int main()
{
    ifstream infile;
    string line;
    infile.open("text");
    if(!infile)
        cout << "error: cannot open file" << endl;
    while(getline(infile, line))
    {
        cout << "line:" << line << endl;
    }
    infile.close();
}

結果

分析

函數原型:istream& getline ( istream &is , string &str , char delim );

is為輸入, str為存儲讀入內容的字符串(不存儲分割符), delim為終結符(不寫默認為'\n')

返回值與參數is一樣

 

同時輸出每行和該行的每一個單詞

代碼

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std;

int main()
{
    ifstream infile;
    string line, word;
    infile.open("text");
    if(!infile)
        cout << "error: cannot open file" << endl;
    while(getline(infile, line))
    {
        cout << "line:" << line << endl;
        istringstream instream(line);
        while(instream >> word)
            cout << "word:" << word << endl;
        cout << endl;
    }
    infile.close();
}

結果

分析

<<是類istream 定義的,istringstream, ifstream 是其子類,都可以用

>>是類ostream 定義的,ostringstream, ofstream 是其子類,都可以用

用讀出的每行初始化字符串流,在輸出賦給單詞(依舊分隔符隔開,但沒有分隔符的事兒)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM