C ++ ifstream I/O?

C ++ ifstream I/O?

本文关键字:ifstream      更新时间:2023-10-16

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

。/fileIO foo。代码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是一个自由函数,而不是成员函数。事实上,应该避免使用成员函数getline。它更难使用,并且可以追溯到标准库中没有string的日子。

字体

getline(codeFileName, line);
应该

getline(codeFile, line);

我想教训是你必须学会如何解释编译器错误消息。

我们都会犯某些类型的错误,并了解它们容易产生的编译器错误。