How to get characters separated by space using scanf

Viewed 60

Here is input.txt

5
A B C D E

I want to get these characters so I used this code:

//...
int n;
fscanf(fp_i, "%d", &n);
//...
char data;
for (int i = 0; i < n; i++) {
    fscanf(fp_i, "%c", &data);
    array_c[i] = data;
}
//...

There were still spaces in array_c, so I tried " %c ", and it worked!

I want to learn of another way to get characters with spaces. Is there a more sophisticated way?

2 Answers

It's fine the way you have it, the only improvement I would suggest it to read directly to the array instead of an intermediate variable data.

for (int i = 0; i < n; i++) {
    fscanf(fp_i, " %c ", &array_c[i]);
}

Note that for array_c to be treated as a string it should have 6 elements, being the 6th element a null-terminator.

You would have:

//...
int n;
fscanf(fp_i, "%d", &n);
char array_c[n + 1];
//...
for (int i = 0; i < n ; i++) {
    fscanf(fp_i, " %c", &array_c[i]);
}
array_c[n] = '\0';
//...

Running sample

Just an additional space in front of %c should work.

int n;
fscanf(fp_i, "%d", &n);

char data;
for (int i = 0; i < n; i++) {
    fscanf(fp_i, " %c", &data); // space front of %c
    array_c[i] = data;
}
Related