首页 > 解决方案 > 如果满足条件,如何不读取下一行?

问题描述

我正在研究读取与此类似的文件(.txt)的项目(C++):

0
40
120
360
440
760
840
1080

我正在使用带有函数 getline() 的 For 循环逐行读取文件,但是在 For 循环中我有一个条件,如果满足该条件,我不想读取下一行,而是,我希望读取文件的指针在循环的下一次迭代中保持在相同的位置。我怎样才能做到这一点?

标签: c++for-loopgetline

解决方案


我建议您使用 阅读该行ifstream,看看这个。然后将其存储到向量或数组中;用于您的目的的伪代码可能如下所示:

#include<iostream>
#include<fstream>
using namespace std;
int main(){
    int array[size];
    ifstream file_num("file.txt");
    for(int i=0;i<size;i++){
        if(condition){
            file_num>>array[i];
        }
   }
        //you can return the index of the position where you want to break and then use it from that index for next iteration;
}

推荐阅读