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!!

13th Nov 2016, 9:26 AM
Eric Lai
Eric Lai - avatar
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.
7th Jan 2017, 1:58 PM
Nemo