IN c++
What would be the code if i want to read a line from a file and this line contains numbers of different data types.I want to be able to save each number in a variabe of the same data type.
Example:
1.24 345 3442
IN c++
What would be the code if i want to read a line from a file and this line contains numbers of different data types.I want to be able to save each number in a variabe of the same data type.
Example:
1.24 345 3442
http://www.cplusplus.com/doc/tutorial/files/
Code:ifstream inf; double d; int n, m; inf.open("foo.txt", ios::in); inf >> d >> n >> m; inf.close();
Last edited by schauerlich; March 19th, 2010 at 07:37 PM.
Posting code? Use the [code] or [php] tags.
I don't care, I'm still free. You can't take the sky from me.
Maybe somthing like:Code:cin >> myfloat >> myint1 >> myint2
what and how the formated operators (<< >>) read is only determined by the type where it should store or output the data. So put a double type on the right side of it and it will read/write doubles
so to read them all into the same type is easy for doubles because an integer is also a valid double representation for streams
double a[3]
somefilestream >> a[0] >> a[1] >> a[2]; // read in any number into doubles
it will also work for other number formats like 3.23e10
the other way round is not valid, if inputed 1.2 when reading ints will read the one and stop at the dot. subsequent integer reads will thus fail when the .2 is not removed from the stream first
Last edited by MadCow108; March 19th, 2010 at 07:49 PM.
After performing the read operations on the stream, verify that all went well with the good() method (or conversely, with fail()).
Code:double d; int m, n; mystream >> d >> m >> n; if (!mystream.good()) { // error parsing data }
Bookmarks