-3

这是我得到的错误:

ambiguous overload for ‘operator>>’ in ‘contestantsInputFile >> contestantName’|

我正在尝试通过引用将文件传递给函数,以便将名称读入名为竞争者名称的变量中。

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

using namespace std;

string contestantName = "";
string contestantName(ifstream &);

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");    
    contestantName(contestantsInputFile);
}


string contestantName(ifstream &contestantsInputFile)
{
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}
4

1 回答 1

1

您试图从 std::istream 读取函数:

contestantsInputFile >> contestantName; //this is the line with the error

也许这更符合您的意图(未经测试):

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

using namespace std;

string readContestantName(ifstream &); // renamed to be a descriptive verb

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");    
    std::string contestantName = readContestantName(contestantsInputFile);

    std::cout << "contestant: " << contestantName << "\n";
}


string readContestantName(ifstream &contestantsInputFile)
{
    std::string contestantName; // new variable
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}
于 2013-10-03T22:06:34.390 回答