我正在尝试C ++文件I / O,特别是fstream。我写了以下代码,到目前为止,它告诉我没有getline成员函数。有人告诉我(并且仍然坚持)有一个成员函数getline。有人知道如何对fstream使用getline成员函数吗?还是从文件一次获取一行的另一种方法?我在命令行中使用了两个文件参数,它们具有唯一的文件扩展名。

./fileIO foo.code foo.encode

#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;
int main( int argc, char *argv[] )
{
  // convert the C-style command line parameter to a C++-style string,
  // so that we can do concatenation on it
  assert( argc == 2 );
  const string foo = argv[1];

  string line;string codeFileName = foo + ".code";

  ifstream codeFile( codeFileName.c_str(), ios::in );
  if( codeFile.is_open())
  {
  getline(codeFileName, line);
  cout << line << endl;
  }
  else cout << "Unable to open file" << endl;
  return 0;
}

最佳答案

getline(codeFileName, line);


应该

getline(codeFile, line);


您传递的是文件名,而不是流。

顺便说一句,您使用的getline是一个自由函数,而不是成员函数。实际上,应该避免使用member function getline。它很难使用,并且可以追溯到标准库中没有string的一天。

07-24 09:46
查看更多