2012-11-05 47 views
0

我正在嘗試編寫一個程序,它將讀取我的文本文件的第一行,然後將該數字輸入到一個int變量中。但我很困惑,因爲如何去做。從.txt文件讀取一行並插入變量

int highscore; // Starting highscore 

    ifstream myfile ("highscore.txt"); 
    if (myfile.is_open()) 
    { 
    while (myfile.good()) 
    { 
     getline(myfile,highscore); 
     cout << highscore << endl; 
    } 
    myfile.close(); 
    } 

但由於某種原因我得到錯誤。 |25|error: no matching function for call to 'getline(std::ifstream&, int&)'|

+0

使用std :: getline intead – billz

+0

什麼是std :: for? – mystycs

+0

找到getline函數的命名空間,就像你的std :: ifstream – billz

回答

1

如果替換,則對getline:

if (myfile >> highscore) 
    cout << "Read " << highscore << '\n'; 
else 
    cout << "Couldn't read an int\n"; 

您可以讀取一個int到高分。你需要使用getline嗎?

+0

完美的作品,但我調整了它,但沒有if和else語句:)爲什麼沒有getline工作? – mystycs

+0

比爾茲答案解釋得很好。你需要先將它讀入一個字符串,然後將其轉換爲一個int。 –