为什么我会收到错误:没有重载函数的实例"getline"与此处的参数列表匹配?

why am I getting a error: no instance of an overloaded function "getline" matches the argument list here?

本文关键字:getline 参数 列表 实例 错误 为什么 函数 重载      更新时间:2023-10-16

我已经查看了几个链接。

不幸的是,我只是为了弄清楚它的新手。我想将以下内容作为while( getline(getline(fin, line) )行,因为我试图从文件中读取整个文本行。然后,我试图弄清楚该文件中是否有任何类似的单词或数字。我正在Microsoft Visual Studio 2012中写这篇文章。

#include <iostream>
#include <fstream>
#include <sstream>
#include <cctype>
#include <string>
using namespace std;
// main application entry point
int main(int argc, char * argv[])
{
    string filename;
    ifstream inFile;
    // request the file name from the user
    cout << "Please enter a filename: ";
    // stores the users response in the string called filename
    cin >> (std::cin, filename);
    // opens the file
    inFile.open(filename.c_str());
    // if the file doesn't open
    if (!inFile)
    {
        cout << "Unable to open file: " << filename << endl;
        return -1;
    } // end of if( !inFile )
    // while( getline(getline(fin, line) ) gives me the same error
    while (getline())
    {}
    // close the file
    inFile.close();
} // end of int main( int argc, char* argv[])

为什么我会遇到错误:no instance of an overloaded function “getline” matches the argument list这里?

因为您打电话给std::getline()没有任何参数,而std::getline()确实需要参数:

while( getline() )
{
}

然而,std::getline()

  1. stream&(输入来自)
  2. std::string&(输入最终输入)
  3. 可选的 a char(一个定界符,默认值为 'n'

这样的事情应该做:

std::string line;
while( std::getline(inFile, line) ) {
  // process line 
}

请注意,您的代码很混乱。让我们浏览它:

int main(int argc, char * argv[])

由于您不使用argcargv,为什么要通过它们?您的编译器应该警告您他们没有使用它们 - 这只是噪音,可能会使您从编译器的诊断中分散注意力,这指出了一个真正的问题。而是这样做:

int main()

警告消失了。

string filename;
ifstream inFile;

当仅进一步使用时,为什么在功能的顶部定义这些?在C 中,将尽可能迟晚定义的样式被认为是很好的样式,最好是在可以初始化时。

using namespace std;

这是一个坏主意,可能会严重伤害您。只是不要做。

cin >> ( std::cin, filename );

我不知道这应该做什么,更不用说它实际上是了。您想要的是:std::cin >> filename。但是,请注意,这可以防止包含空格的文件名。这应该是问题,而是使用std::getline()

inFile.open( filename.c_str() );

这是inFile应该定义的地方:

std::ifstream inFile( filename.c_str() );

最后,您对文件的明确关闭

inFile.close();

是不必要的。无论如何,std::ifstream的破坏者会照顾好。

相关文章: