I have something as below in c++.
I want to read a file for several times, but failed.
Though I use fseek to move to the head of the file after I freopen again, but I still can only read it once. For the second time, cin get nothing @.@.
I'm really confused with it.
(It seems c's freopen can work, but I really want to use cin ...)
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main(){
for (int i=0; i<2; i++) {
freopen("windmill02.mtl", "r", stdin);
fseek(stdin, 0, 0);
string s0, name, filename;
while (cin>>s0) {
cin>>name;
cin>>filename;
cout <<name<<" "<<filename<<endl;
}
freopen("ke.txt","r",stdin);
}
return 0;
}
Mixing C and C++ to read a file is not really recommended. It works at the beginning but it seems by seeking on
stdin
, it gets de-synchronized withcin
which is always at the end of file. Since you did everything in C, here's a version that work using scanf instead: