上一篇文章,我们讲到:C、C++ 标准输入重定向 & 万能头 - 编程技巧 https://cloud.tencent.com/developer/article/1767052;
然而,在重定向过程中,我们需要从文件中循环读入;这时候我们需要使用下面几个方法:
bash-3.2$ cat in.txt
1 2 3 4 5 6 7 8bash-3.2$
bash-3.2$ cat in.txt
1 2 3 4 5 6 7 8 bash-3.2$
方法1和方法3在上面两种情况中表现相同;方法2 会因为文件尾的空格,产生i计数的不同;具体可以自行测试;
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
vector<int> inarray;
int main(){
freopen("in.txt", "r", stdin); // 重定向到输入
int i = 0;
int tmp;
// 方法1
while (cin >> tmp)
{
inarray.push_back(tmp);
cout << inarray[i] << endl;
i++;
}
// 方法2
while (!cin.eof()){
cin >> tmp;
inarray.push_back(tmp);
cout << inarray[i] << endl;
i++;
}
// 方法3
while (scanf("%d", &tmp) != EOF)
{
inarray.push_back(tmp);
cout << inarray[i] << endl;
i++;
}
cout << inarray.size()<< endl;
cout << i << endl;
return 0;
}
但是这几个方法又有所不同;cin.eof() 每行的最后,还是有空格或者回车的时候,还是对增加i的计数;所以在实际过程中,为了判断边界值,我建议使用方法1 和 方法3;方法1 因为tmp是 int 类型,简介得进行了格式化;