如何从文本文件的每一行获取一个 int ?
我有一个年份列表:
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
我试图找出如何从每一行中获取年份..
我一直在网上阅读,到目前为止我读了 getline 但我想这行不通,因为它只适用于字符串。
我还能用什么?
附言。这是我的代码
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;
}
I have a list of years:
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
and i' trying to find out how to grab the year from each line..
I have been reading online, so far I read getline but I guess that won't work since it works with only strings.
what else can I use?
PS. here is my code
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用标准流 IO:
You can use standard stream-IO:
如果您完全确定该文件包含行,请读取它们,然后使用
strstream
来解析它们。If you're completely sure that the file has lines, read them and then use
strstream
s to parse them.获得字符串后,使用 [strtok]http://www.cplusplus.com/参考/clibrary/cstring/strtok/ 或任何相关 api,后跟 isdigit() 以检查其是否不是字母数字,后跟 atoi()
选择您可用的 api。
once you get the string, use [strtok]http://www.cplusplus.com/reference/clibrary/cstring/strtok/ or any related api followed by isdigit() to check if its not alphanumeric and followed by atoi()
chose the apis available to you.