13

C++ では、抽出せずに '\n' の区切り記号まで行を読み取ることができる関数が fstream ライブラリ (または任意のライブラリ) にありますか?

peek() 関数を使用すると、プログラムが次の文字を抽出せずに読み込んで「覗く」ことができることはわかっていますが、行全体に対してそれを行う peek() のような関数が必要です。

4

1 に答える 1

19

getlinetellgおよびの組み合わせでこれを行うことができますseekg

#include <fstream>
#include <iostream>
#include <ios>


int main () {
    std::fstream fs(__FILE__);
    std::string line;

    // Get current position
    int len = fs.tellg();

    // Read line
    getline(fs, line);

    // Print first line in file
    std::cout << "First line: " << line << std::endl;

    // Return to position before "Read line".
    fs.seekg(len ,std::ios_base::beg);

    // Print whole file
    while (getline(fs ,line)) std::cout << line << std::endl;
}
于 2012-04-22T14:49:29.053 に答える