After the standard input redirected to a file, how to continuously read, how to determine the end of the standard input stream? cin.eof ();

Last article, we talked about: C, C ++ standard input redirection & Universal head - programming skills  https://www.cnblogs.com/xuyaowen/p/c-cpp-reopen.html ;

However, the redirection process, we need to loop to read from a file; this time we need to use the following several methods:

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$ 

Methods 1 and 3 showed the same in both cases above; method 2 because the space end of the file, i have different count; specifically self-testing;

#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;
}

However, these methods will also be different; finally, there is still a space or carriage return when cin.eof () per line, or to increase i counted; so in the actual process, in order to determine the boundary value, I recommend using methods 1 and 3; method 1 because tmp is of type int profile have been formatted;

Guess you like

Origin www.cnblogs.com/xuyaowen/p/cpp-cin-eof.html