Reputation: 3
so the title says everything and i created a VERY simple code just to test this, and i cant get it to work. The file has one line and it is "asd dsa:1 2 3" i want to store "asd dsa" in a string variable, and each number in a different int variable. this is the code:
#include<stdio.h>
int main(){
FILE *fp;
fp=fopen("file.dat","r");
char aa[20];
int a, b, c;
fscanf(fp, "%[^:]%d %d %d", aa, &a, &b, &c);
printf("%s %d %d %d\n", aa, a, b, c);
return 0;
}
and the output is
asd dsa 21911 1313271752 32720
so it is reading only the string.
Upvotes: 0
Views: 322
Reputation: 591
I highly suggest in the future to learn how to debug your code. To be honest, I did not found the solution right at the top so I copied the code, and ran in on my machine and I got the wrong output, like you. Then, I debugged my code and I noticed the string is read correctly, and the numbers remain untouched. To make sure, I created a variable to hold the return value from scanf, and indeed it was 1 since only the string was getting the input.
I then first tied to add a space between %[^:]
and %d
, but to no avail. Then I looked at the file again, and the string I got on aa
variable and noticed the :
was in the file, but not in aa
. Where did it go? nowhere, it was still in the buffer waiting to be read. In order to "skip" it, you could just add :
sign after %[^:]
, so the command would "eat it", and after doing it on my machine it worked.
The short answer, is to change the scanf line to:
fscanf(fp, "%[^:]:%d %d %d", aa, &a, &b, &c);
The long answer, is to learn how to debug you code correctly, It took my less than 2 minutes to figure it out and I'm sure that if you tried yourself, you could find the solution too.
Of course if you try debugging yourself with no avail, you are always welcome to open a topic!
Upvotes: 1