You are here:

C/Read line of data and then manipulate it

Advertisement


Question
Hi Narendra,

Here is a sample data file:
0 400 34.0000123 0 -23.9 0 -4 5000 -1 test2.txt
0 40 762 232.98983 0 0 50 1000 1 test2.txt

each line basically consists of numbers and at the end of the line the name of text file the results will be saved in. I want the program to read the the data one line at a time. Say it reads line one then I want to assign values to variables as follows:
var1 = 0;
var2 = 400;
var3 = 34.0000123;
.
.
.
var10 = test1.txt

I used fgets() to read line by line but don't know how to manipulate it further.

Regards,
Zia

Answer
Since you are using fgets() to read till the end of line, each line will be strored in a string.
Now, use sscanf() to read and parse this string.
Suppose, your string variable is my_str, then you can do:
int data1, data2, data3, data4, data5, data6, data7, data8, data9;
char filename[16] = "";
sscanf(my_str, "%f %f %f %f %f %f %f %f %f %s, data1, data2, data3, data4, data5, data6, data7, data8, data9, filename);

-Narendra

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.