While importing data from a file, I bumped into an import error while using fscanf(input, "%d", &myint);
. Sometimes it took me a while to find out that I should've used fscanf(input, "%d\n", &myint);
instead, which fixed the problem.
I know that there are other ways to import a line, but I have a doubt about this specifically.
My doubt arises from the fact that in the programming book I use (in the paragraph about the fscanf
function) this information is missing, and, indeed, it imports integers without '\n', which personally caused me an error.
Here are the first three lines of my input file:
3
2 3
6 6
And here are the instructions I've used:
fscanf(input, "%d\n", &playersnum);
fscanf(input, "%d %d", (dicethrows+(i*2)), (dicethrows+(i*2)+1))
where dicethrows
is a pointer to an int
array. As you can see, in the last instruction (which is actually in a for
loop with counter i
) I didn't need to use '\n', but without it in the first line still caused me reading issues...
My question is, when should I add a '\n' in my fscanf
and why?
EDIT: Adding some code (sorry for not translating the variables' names, I think it doesn't really matter as the code is quite short):
int main(void) {
int numerogiocatori;
int numerolanci=0;
int* posizionigiocatori;
int* lancidadi;
//impor data
FILE* input=fopen("info.txt", "r");
if(input!=NULL) {
//first thing: first line (number of players)
fscanf(input, "%d\n", &numerogiocatori);
posizionigiocatori=malloc(numerogiocatori);
for(int i=0; i<numerogiocatori; posizionigiocatori[i]=1, i++); //all players start from position 1
//second thing: count lines after the first one (=number of throws)
do {
int ch=fgetc(input);
if((char)ch=='\n' || ch==EOF) {
numerolanci++;
if(ch==EOF)
break;
}
} while(true);
lancidadi=malloc(sizeof(int)*2*numerolanci);
//third thing: import throws
fseek(input, 0, SEEK_SET);
fscanf(input, "%*d\n");
for(int i=0; fscanf(input, "%d %d", (lancidadi+(i*2)), (lancidadi+(i*2)+1)) != EOF; i++);
fclose(input);
}
...
Before posting I tried to check a second time and the values I get are actually different.