【问题标题】:why am I getting a error: no instance of an overloaded function "getline" matches the argument list here?为什么我收到错误:没有重载函数“getline”的实例与此处的参数列表匹配?
【发布时间】:2014-02-16 23:04:10
【问题描述】:

我查看了几个链接,例如 thisthis

不幸的是,我只是一个程序员的新手才能弄清楚。我想将以下内容作为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[])

【问题讨论】:

  • 只是好奇:你认为cin &gt;&gt; (std::cin, filename) 会做什么?
  • 我认为是这样的://将用户响应存储在名为 filename 的字符串中,但在您发表评论后,看来我完全错了。
  • 不,它这样做是对的,只是你以不必要的方式这样做。 (std::cin, filename)filename 相同,因为逗号运算符 , 返回最右边的操作数。你真正需要的是std::cin &gt;&gt; filename
  • 完整的错误信息是什么?

标签: c++ compiler-errors getline file-io


【解决方案1】:

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

因为您调用std::getline() 时没有任何参数,而std::getline() 确实需要参数:

while( getline() )
{
}

然而,std::getline() 需要的是

  1. stream&amp;(输入来自哪里)
  2. std::string&amp;(输入结束的地方)
  3. 可选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;

might hurt you badly 是个坏主意。只是不要这样做。

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

我不知道它应该做什么,更不用说它实际上做了什么,假设它可以编译。相反,您想要的是:std::cin &gt;&gt; filename。但是请注意,这会阻止文件名包含空格。如果这是一个问题,请改用std::getline()

inFile.open( filename.c_str() );

这是应该定义inFile的地方:

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

最后,你明确关闭文件

inFile.close();

是不必要的。 std::ifstream 的析构函数无论如何都会处理这个问题。

【讨论】:

  • 执行此操作时仍然出现错误:while(getline(fin, line)) {}
  • @user26093 我认为您向我们展示的代码不是您实际拥有的代码......请向我们展示您实际拥有的代码。跨度>
  • @user26093 getline(fin, line))? fin 是什么?
  • 是的。它给了我同样的错误。 fin 应该是 fileIn。
  • 我只是想读入文件的每一行,处理它,然后读入下一行..
猜你喜欢
  • 2023-03-10
  • 2014-12-27
  • 2013-11-17
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多