0
Problem on fstream
how to change scanf inâ for(p=b; scanf("%c",p) && isspace(*p);); andâ sscanf(data0.c_std(),"%d",&x); I will use fstream to read from a in.txt and to wright to out.txt but when I change them to fscanf is error!!
1 Answer
+ 1
Bit late to the party, but lessee...
For the first line (Who came up with this code? This is really bad)
for (p = b; scanf("%c", p) && isspace(*p); );
You could change this to use fstream by
std::fstream File(FileName);
//...
for (int c = 0; (c = File.get()) != EOF && isspace(c); );
This just keeps reading it byte by byte until it encounters a non-space character or the end of the file, at which point it moves to your next line of code. Take note of the ; after the line, making it an empty loop.
For reference, check out:
http://www.cplusplus.com/reference/istream/istream/get/
The second line,
sscanf(data0.c_str(), "%d", &x);
I'm assuming c_std() was supposed to be c_str().
With fstream, you can instead just do
std::fstream File(FileName);
int x = 0;
//...
File >> x;
Much easier to follow, no?
For reference, check out:
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
Just a heads up, I'm doing these from memory so there MIIIGHT be an issue with the first one, particularly with the EOF.