【问题标题】:C++: #included <fstream> but cannot use getline?C++:#included <fstream> 但不能使用 getline?
【发布时间】:2013-01-16 05:18:41
【问题描述】:

我的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
.
.
.

void function() {
    ofstream inputFile;
    .
    .
    .
    inputFile.getline (inputFile, inputField1, ",");
}

由于某种原因我无法弄清楚,使用 g++ 编译它会返回

error: ‘struct std::ofstream’ has no member named ‘getline’

另外,作为旁注,它也会产生错误

error: invalid conversion from ‘void*’ to ‘char**’
error: cannot convert ‘std::string’ to ‘size_t*’ for argument ‘2’ to ‘ssize_t getline(char**, size_t*, FILE*)’

但我认为我的参数是错误的。

谁能帮忙解释一下?

【问题讨论】:

  • 似乎有多个问题:ofstream 用于输入,您似乎正试图读入std::string(因此istream 中的成员函数getline 将不起作用要么...)谷歌getline并找到需要std::string的免费函数

标签: c++ string getline


【解决方案1】:

在 c++ 中有两个 getline 函数使用分隔符。

一个在 ifstream 中:

istream& getline (char* s, streamsize n, char delim);

另一个在字符串中:

istream& getline (istream& is, string& str, char delim);

从您的示例看来,您正在预期使用字符串中的一个。

#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;

int main() {
  ifstream inputFile;
  string inputField1;

  inputFile.open("hi.txt");

  getline(inputFile, inputField1, ',');

  cout << "String is " << inputField1 << endl;

  int field1;
  stringstream ss;
  ss << inputField1;
  ss >> field1;

  cout << "Integer is " << field1 << endl;

  inputFile.close();

}

【讨论】:

  • 我的程序中inputField1的类型是int。这也一样吗?
  • 如何指定要使用 ifstream 或 string 中的哪一个?
  • 上面的程序将第一个字段读入一个字符串。要将其转换为整数,请使用字符串流。要使用 ifstream 中的 getline,请参阅下面的 Carl Norum 代码。请注意,它使用 inputFile.getline(),而不仅仅是 getline()。并且它期望的字段类型是不同的。 getline from string 读取到一个字符串,该字符串是动态分配的。如果您事先不知道正在阅读的字段的最大长度,这很有用。 ifstream getline 只能读取到缓冲区的预分配大小。
【解决方案2】:

ofstream 是一个输出文件流。你需要一个 ifstream。

【讨论】:

    【解决方案3】:

    ofstream 是一个输出 流,因此它没有任何输入方法。你可能想要ifstream:

    void function() {
        ifstream inputFile("somefilename");
        char buf[SOME_SIZE];
        inputFile.getline (buf, sizeof buf, ',');
    }
    

    【讨论】:

      【解决方案4】:

      ofstream 是一个输出流,因此 getline 方法没有意义。也许你需要ifstream

      【讨论】:

        猜你喜欢
        • 2013-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        相关资源
        最近更新 更多