scanf - Easiest/clearest way to read formatted data in C++ -


i'm reading in file of space/newline delimited numbers. after trying stringstreams , ifstreams, appears c++ hasn't improved on fopen , fscanf simple task in terms of simplicity, readability, or efficiency.

what robustness? since check fscanf returned number of items expect, doesn't seem issue. benefit can think of stringstream's giving more options handle failure.

here quick example using fscanf:

file * pfile; pfile = fopen ("my_file.txt","r"); if( pfile == null ) return -1;  double x,y,z; int items_read; while( true ) {     items_read = fscanf( pfile, "%lf %lf %lf", x, y, z );     if( items_read < 3 ) break;  // checks eof (which -1) or reading 1-2 numbers      std::cout << x << " " << y << " " << z << "\n"; } 

note: security, replace fopen/fscanf fopen_s/fscanf_s in visual studio.

in experience neither c nor c++ offer "robust input tolerates idiot users".

it adequate "well formed input it's ok 'something wrong in input, please fix it'...", not robust situations need check (e.g. putting 2 instead of 3 numbers on line, whole rest of data happily acceped, z values x values, , else "shifted one").

in case, need write functions appropriate checking reading line, checking can fetch 3 numbers out of line - or that. may find using stringstream or similar adequate checking there 3 valid numbers on line, using f >> x >> y >> z; lead next line being used satisfy whatever missing on line.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -