在 C++ 中,fstream 库(或任何库)中是否有一个函数允许我读取一行到“\n”分隔符而不提取?
我知道 peek() 函数允许程序“窥视”其读取的下一个字符而不提取,但我需要一个类似 peek() 的函数来执行此操作,但对于整行。
您可以结合使用以下方法来完成此操作getline
, tellg
and 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)