2012-04-22 389 views
7

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

我知道偷看()函数允许程序在下一字符的阅读,而不提取“偷看”,但我需要一个像偷看函数,这是否(),但对于整条生产线。

+0

,这是什么您的使用情况?听起来有点像XY问题。 – 2012-04-22 14:44:12

+0

它读取一个文本文件,并从它我想要使用一个peek()类似的函数来确定是否读入的下一个值是一个句子字符串或不。下面的方法对我的问题完美工作。 – SexyBeastFarEast 2012-04-24 07:22:28

回答

11

您可以使用getline,tellgseekg的组合执行此操作。

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

感谢克莱斯特这个方法完美地工作!所以我假设没有偷看()函数读取一行? – SexyBeastFarEast 2012-04-23 14:31:47

+0

没错,没有这种偷看功能。 – Kleist 2012-05-02 15:07:18