如何让我的std::fstream
对象从第二行开始读取文本文件?
发布于 2008-10-02 20:15:38
使用getline()读取第一行,然后开始读取流的其余部分。
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
...
(更改为std::getline (感谢dalle.myopenid.com))
发布于 2008-10-02 21:29:44
您可以使用流的忽略功能:
ifstream stream("filename.txt");
// Get and drop a line
stream.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
// Get and store a line for processing.
// std::getline() has a third parameter the defaults to '\n' as the line
// delimiter.
std::string line;
std::getline(stream,line);
std::string word;
stream >> word; // Reads one space separated word from the stream.
读取文件时的一个常见错误:
while( someStream.good() ) // !someStream.eof()
{
getline( someStream, line );
cout << line << endl;
}
这失败的原因是:当读取最后一行时,它没有读取EOF标记。因此,流仍然是好的,但是流中没有更多的数据可供读取。因此,循环被重新进入。然后,std::getline()尝试从someStream读取另一行并失败,但仍将一行写入std::cout。
简单的解决方案:
while( someStream ) // Same as someStream.good()
{
getline( someStream, line );
if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true
{
// Only write to cout if the getline did not fail.
cout << line << endl;
}
}
正确的解决方案:
while(getline( someStream, line ))
{
// Loop only entered if reading a line from somestream is OK.
// Note: getline() returns a stream reference. This is automatically cast
// to boolean for the test. streams have a cast to bool operator that checks
// good()
cout << line << endl;
}
发布于 2008-10-02 20:18:39
调用getline()一次以丢弃第一行
还有其他的方法,但问题是,你不知道第一行有多长,对吧?所以你不能跳过它,直到你知道第一个'\n‘在哪里。然而,如果你确实知道第一行有多长,你可以简单地寻找它过去,然后开始阅读,这会更快。
因此,第一种方法看起来像这样:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
// Open your file
ifstream someStream( "textFile.txt" );
// Set up a place to store our data read from the file
string line;
// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );
// Now begin your useful code
while( !someStream.eof() ) {
// This will just over write the first line read
getline( someStream, line );
cout << line << endl;
}
return 0;
}
https://stackoverflow.com/questions/164344
复制相似问题