1

I was wondering how to read data from a text file that has its data separated by a comma; for example line 1 of the text file says: (Name,Integer,Integer).

So I tried using this code to read the code in but it didn't work:

while (fscanf(ifp, "%15s,%d,%d", stationName, &stationDistance, &stationDirection ) == 2) { strcpy(q[fileCounter].name, stationName); q[fileCounter].distance = stationDistance; q[fileCounter].direction = stationDirection; printf ("Station Name: %s \t Distance to Central: %d \t Direction from Central: %d \n", q[fileCounter].name, q[fileCounter].distance, q[fileCounter].direction); fileCounter++; } 
0

1 Answer 1

2

If Name contains spaces, then the format specifier that you are using will stop there and fail, you would need

while (fscanf(ifp, "%15[^,],%d,%d", stationName, &stationDistance, &stationDirection) == 3) { } 

The [ specifier matches against the set of characters you specify inside the [] for example "%[0-9]" matches all digits from 0 to 9, the ^ symbol tells fscanf() to match antything that is not the characters enclosed by [] and following the ^, so you are matching anything except the , which is what you want.

In contrast the "%15s" specifier consumes all characters until 15 characters have appeared or a white space character as in isspace(chr) != 0 have appeared which is why I suppose that your fscanf() was only matching two of the three values.

You was comparing the return value of fscanf() to 2 instead of 3 which I guess was because it was returning 2 instead of 3 and you knew that because otherwise the loop was not entered, well that is a really bad thing to do, because you are causing undefined behavior since one of the three parameters might not be initialized by scanf() yet, you copy the name with strcpy() and store the integers too.

Sign up to request clarification or add additional context in comments.

13 Comments

Wow you taught me so much just that, I had no idea you could of done anything of that, thank you so much, however for some reason it doesn't go into the loop now?
I will need you to post data from the input file then.
The data goes as following: "Taren Point,10,S" -> next line "Ashfield,6,W"
The last value is not an integer, you cant read it with "%d", why is the field an integer?
Thank you so much, stupid error
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.