TimelordViktorious
TimelordViktorious

Reputation: 336

Reading in a text file with comma's

I am trying to use fscanf to read in from infile (which is either stdin or a file) for a file that is represented like this:

1,2,3
4,5,6

Do ignore the fact that they are numbers - I am representing them as strings.

What I did was I used

fscanf(infile, "%s%*c %s%*c %s%*c[^\n]", x, y, z); where x, y, z are string variables. 

I am expecting that each represent digit, on that line, gets stored in x, y, z, but it is not working, and is instead storing the entire line in x alone.

Any help please? Thanks.

Upvotes: 1

Views: 78

Answers (2)

jamesdlin
jamesdlin

Reputation: 90115

If you must use scanf/fscanf, then you want to use %[^,] as the input formatter instead of %s. %s will greedily read as much as it can; %[^,] will read a string consisting of characters (including whitespace) that are not ,:

fscanf(infile, "%[^,],%[^,],%[^,]", x, y, z);

Do note that the above usage of fscanf is unsafe because it does nothing to limit the number of characters read into each string. Consequently, it is completely susceptible to buffer-overflow attacks.


Personally, I would read the entire line with fgets (or getline if available) and then tokenize it on , with strtok. scanf/fscanf are notoriously hard to use correctly and usually should be avoided.

Upvotes: 0

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

You are using '%s' which will read an entire word upto spaces. So 1,2,3 is read in x for the first line.

What you need to do is take x, y and z as integers, Then you can read three integers and convert it to a string using a variety of methods (e.g. itoa

int x,y,z;
char x_str[20], y_str[20], z_str[20];
//...
fscanf(infile, "%d,%d,%d", x, y, z);
itoa{x,x_str,10);  // and so on

Upvotes: 1

Related Questions