【问题标题】:C++ fstream function that reads a line without extracting?C ++ fstream函数读取一行而不提取?
【发布时间】:2012-04-22 14:38:25
【问题描述】:

在 C++ 中,fstream 库(或任何库)中是否有一个函数允许我在不提取的情况下读取一行到 '\n' 的分隔符?

我知道 peek() 函数允许程序在不提取的情况下“窥视”它读取的下一个字符,但我需要一个类似 peek() 的函数来做到这一点,但要针对整行。

【问题讨论】:

  • 你的用例是什么?听起来有点像 XY 问题。
  • 它读取文本文件并从中我想使用 peek() 之类的函数来确定读取的下一个值是否是句子字符串。下面的方法非常适合我的问题。

标签: c++ fstream extraction peek


【解决方案1】:

您可以结合使用getlinetellgseekg

#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;
}

【讨论】:

  • 感谢 Kleist,此方法非常有效!所以我假设没有像 peek() 这样读取一行的函数?
  • 没错,没有这样的窥视功能。
  • tellg 返回 std::streampos 所以应该使用它而不是 int
  • 很遗憾,它不能存在于 const 函数中,而且它可能不是线程安全的。
猜你喜欢
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2018-02-06
  • 2013-10-20
相关资源
最近更新 更多