2013-10-03 92 views
-3

這是我得到的錯誤:爲「運營商>>」曖昧超載

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

我想引用爲了傳遞一個文件的功能來讀取一個名字到一個變量稱爲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; 
} 
+0

你在哪裏聲明變量'contestantName'? – yan

+0

您沒有稱爲'contestantName'的變量。 – juanchopanza

+0

哎呀。實際上我確實有一個名爲contestantName的變量,但我不小心沒有在這個問題中包含它,因爲我試圖減少人們必須閱讀的代碼行數。我現在添加了變量。 – user2234760

回答

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; 
}