gpt4 book ai didi

c++ - 为什么我收到错误: no instance of an overloaded function “getline” matches the argument list here?

转载 作者:行者123 更新时间:2023-12-02 11:10:55 25 4
gpt4 key购买 nike

我看了几个链接,例如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[])

最佳答案

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



由于您不带任何参数调用 std::getline(),而 std::getline()确实需要参数:
while( getline() )
{
}

但是, std::getline()需要的是
  • 一个stream&(输入来自何处)
  • 一个std::string&(输入结束)
  • (可选)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 >> filename。但是请注意,这可以防止文件名包含空格。如果有问题,请改用 std::getline()
    inFile.open( filename.c_str() );

    这是应该定义 inFile的地方:
    std::ifstream inFile( filename.c_str() );

    最后,您明确关闭文件
    inFile.close();

    是没有必要的。无论如何, std::ifstream的析构函数会解决这个问题。

    关于c++ - 为什么我收到错误: no instance of an overloaded function “getline” matches the argument list here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358322/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com