简体   繁体   中英

How to read first numbers from file in C++

I have txt file like this.

51.5u-07
-6.5 -10      
55u-10
-7 -10    
55u-10
-7 -10    
55u-10
-7 -10    
54u-10
-7 -10    
54.5u-10
-7 -10    
55u-10
-7 -10    
54.5u-10
-7 -10    
55.5u-10
-7.5 -10

I want to read this file, get all odd line's value into vector of int, vec1. get all even line's value into vector of int, vec2.

such as vec1 is [51.5, 55,55,55,... vec2 is [-6.5, -7, -7, -7...] can anybody help me this?

Thank you.

You can read both numbers at once using fscanf :

double first;
int second;
scanf("%lf%*[ u]%d", &first, &second);

The "magic" is in the format string: it reads a double using %lf , then skips a space or a u using %*[ u] , and finally reads an int using %d . Do this in a loop, pushing the first and the second variables onto the two vectors as needed.

Demo on ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM