【发布时间】:2014-06-02 14:28:39
【问题描述】:
以下文件打印文件的第二行:
#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;
}
我想问我如何写入该文件,我问是因为如果我使用
ofstream 而不是ifstream 我不能使用getline 函数,如果我使用ofstream 我不能写入那个文件。
如果我使用ifstream 并尝试写入该文件,我会收到错误消息:
IntelliSense:没有运算符“
【问题讨论】:
-
分两个单独的步骤进行,一个是使用
ifstream读取所有输入,然后关闭另一个ofstream以写入此文件。 -
相关,在循环中检查
eof很可能不是您想要的 (Why is iostream::eof inside a loop condition considered wrong?)。您应该将整个getline调用作为 while 条件。
标签: c++ file ifstream getline ofstream