2012-11-05 46 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。 –