2012-04-16 83 views
3

我不明白爲什麼這不起作用。出於某種原因,我得到的錯誤:Cin沒有操作數>>

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)

我在Visual Studio2010 C++快遞這樣做是否有幫助。不知道爲什麼它交給我這個錯誤,我使用cin做其他節目...

我的代碼:

#include <iostream> 
#include <iomanip> 
#include <fstream> 
using namespace std; 

int main(int argc, char* argv){ 
    string file; 

    if (argc > 1) 
    { 
     file = argv[1]; 
    } 
    else 
    { 
     cout << "Please Enter Your Filename: "; 
     cin >> file; 
    } 
} 
+6

'#include ' – 2012-04-16 23:20:48

回答

6

包括<string>

最重要的是我建議你使用函數getline不是作爲>>將在你輸入第一個字停止。

例子:

std::cin >> file; // User inputs C:\Users\Andrew Finnell\Documents\MyFile.txt 

結果是「C:\用戶\安德魯」,頗爲意外考慮到數據不被消耗,直到換行,並在未來的std :: string讀就會自動消耗並填充「Finnell \ Documnts \ MyFile.txt」

std::getline(std::cin, file); 

這將消耗所有文本,直到換行。

+0

+1在我的電話中。 – 2012-04-16 23:25:59

+0

你是什麼意思的「>>不適用於std :: string的」? – 2012-04-16 23:27:10

+0

@EdS。謝謝。 – 2012-04-16 23:28:49

1

你忘了包括<string>,這是在該函數的定義。請記住,每種類型都將其自己的operator>>定義爲通過流操作的靜態函數。輸入流不可能寫入將來可能創建的所有類型,因此它被擴展到這種方式。