【发布时间】:2017-10-16 06:24:49
【问题描述】:
我正在尝试在 C++ 中创建一个函数,该函数从文件中读取所有行,然后将所有行连接成一个字符串,然后返回该字符串。这是我用来完成此操作的代码:
// at the top of the file
#include "string_helper.hpp" // contains definition for function
#include <vector>
#include <string.h> // used in another function within the same file
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
// the code I believe to be problematic
ifstream input("file.txt");
string result(0);
string line;
while (std::getline(&input,&line)) {
result += line;
}
但是,当我尝试编译此代码时,我收到此错误:
<project root>/src/string_helper.cpp:52:35: error: no matching function for call to ‘getline(std::ifstream (*)(std::__cxx11::string), std::__cxx11::string*)’
while (std::getline(&input,&line)) {
^
In file included from /usr/include/c++/6.3.1/string:53:0,
from include/string_helper.hpp:22,
from <project root>/src/string_helper.cpp:19:
我查看了www.cplusplus.com,它列出了getline的定义:
istream& getline (istream& is, string& str);
我很困惑,因为我在 while 循环的声明中使用了 & 符号,但编译器仍然说我使用了不正确的参数。
编辑:原来我不小心创建了一个函数。 input 的真正声明是:
ifstream input(string(filename));
因为我必须从 char * 解析 filename。我没有将其包含在原始代码中,因为我试图使其通用,以便适用于许多人。我对 C++ 比较陌生。只需在 input 的声明之外创建字符串即可解决问题。所以我做了:
string fname(filename);
ifstream input(fname);
对不起。
【问题讨论】:
-
&用在不同的地方意味着不同的东西。一本好的 C++ 书籍会涵盖这一点。 -
代码和错误消息不匹配 -- 除非您点击 most vexing parse,或者有一个名为
input的函数。错误消息表明您传递的第一个参数是函数指针。
标签: c++ ifstream getline istream