天天看點

【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();
}      

結果

【c++】輸出檔案的每個單詞、行

分析

定義檔案流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();
}      

結果

【c++】輸出檔案的每個單詞、行

分析

函數原型: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();
}      

結果

【c++】輸出檔案的每個單詞、行

分析

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

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