C ++移至file.txt中的下一个元素 [英] c++ moving to next element in a file.txt
本文介绍了C ++移至file.txt中的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个愚蠢的问题. 我有一个.txt文件.打开后,我只需要输入数字并跳过单词. 有什么方法可以检查下一个元素是否是单词?
i have a stupid question. I have a .txt file. Once opened, i need to take only numbers and skipping words. Is there any method to check if next element is a word or not?
因为我的文件像:word 1 2 word 1 2 3 4 5 6 ...
Because my file is like: word 1 2 word 1 2 3 4 5 6...
int n,e;
string s;
ifstream myfile("input.txt");
所以我认为这是一个愚蠢的方法,可以避免使用字符串的问题,并将内容放入字符串中,然后取数字,就像这样:
and so i think that's a stupid method to avoid the problem using a string and put the content in a string and then taking numbers, right like this:
myfile >> s;
myfile >> n;
myfile >> e;
推荐答案
您可以执行以下操作
int num = 0;
while(myfile >> num || !myfile.eof()) {
if(myfile.fail()) { // Number input failed, skip the word
myfile.clear();
string dummy;
myfile >> dummy;
continue;
}
cout << num << endl; // Do whatever necessary with the next number read
}
在此处查看完整的工作示例
这篇关于C ++移至file.txt中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文