如何从文本文件中的每一行中获取一个int?

0 c++ int file-io

我有一个年份列表:

1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
Run Code Online (Sandbox Code Playgroud)

我试图找出如何从每一行抓住年份..

我一直在网上阅读,到目前为止我读了getline,但我想这不会起作用,因为它只适用于字符串.

我还能用什么?

PS.这是我的代码

int main(int argc, char *argv[]) {

    string line;
    ifstream myfile ("leapin.txt");
    if (myfile.is_open()){
        while ( myfile.good() ){
            getline (myfile, line);
        }
        myfile.close();
    }

    else cout << "Unable to open file";

      system("PAUSE");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 6

您可以使用标准流IO:

#include <fstream>

int main() {
    std::ifstream input("filename.txt");
    int buffer;
    while(input >> buffer) {
        // do stuff with the number
    }
}
Run Code Online (Sandbox Code Playgroud)