C++ では、抽出せずに '\n' の区切り記号まで行を読み取ることができる関数が fstream ライブラリ (または任意のライブラリ) にありますか?
peek() 関数を使用すると、プログラムが次の文字を抽出せずに読み込んで「覗く」ことができることはわかっていますが、行全体に対してそれを行う peek() のような関数が必要です。
C++ では、抽出せずに '\n' の区切り記号まで行を読み取ることができる関数が fstream ライブラリ (または任意のライブラリ) にありますか?
peek() 関数を使用すると、プログラムが次の文字を抽出せずに読み込んで「覗く」ことができることはわかっていますが、行全体に対してそれを行う peek() のような関数が必要です。
getline
、tellg
およびの組み合わせでこれを行うことができます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;
}