using while and getline to split data of a input file and assign different columns to different variables in C

StackOverflow https://stackoverflow.com/questions/22297699

  •  12-06-2023
  •  | 
  •  

Question

how to split the line read from a file in C and assign values from different columns to different variables?

I have a .txt file in which each line contains 4 integer values separated by a tab. I have to store first value in some variable , say a second value in another variable , say b third value in another variable, say c.

and then pass a, b and c as arguments to a function.

And then read the next line from file and doing same as above until end of file. I am trying to use getline.

Input file has this kind of data:

1   2   3   4   
7   4   3   2
3   2   5   4
2   98  876 989

in one iteration

I want

 a=1
 b=2
 c=3
 int r=func(a,b,c)
 //some code based on the value of r, such as writing this to a file.

Now reading next line a=7 b=4 c=3

again function calling. Q1. how to split data?

Q2. how to assign to different variables?

But not able to come up with any satisfactory solution. could you help me in this please?

Thanks :)

Was it helpful?

Solution

to rad the data into variables directly from a file you can use,

fscanf(file,"%d %d %d",a,b,c);

your input file has 4 numbers so you need to neglect it so you can use,

while(fscanf(file,"%d %d %d %d\n",a,b,c,d)==4)
{

 r=func(a,b,c);
 //some code using value of r
}

you can use code similar to this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top