Pergunta

Edit: Oops, forgot to say this is C

I have a .txt file with the following:

    blabla, 213, 32

I want to store the first string in a variable, so I do this:

    char x[6];
    int y, z;
    fscanf(finput, "%s, %d, %d", x, y, z)

but when I print "x" I get:

    blabla,

and the rest of the text does not get stored correctly.

What I find weirdest is that my array x has the same number of "spaces" as blabla has characters, but it still stores seven characters.

A workaround would be to read each character and store them individually, but I would like to do it as a string if possible.

Foi útil?

Solução

First, this line

fscanf(finput, "%s, %d, %d", x, y, z)

should be fixed to eliminate undefined behavior:

fscanf(finput, "%s, %d, %d", x, &y, &z)
//                              ^   ^
//                              |   |
// You need to take an address of int variables

If you do not want the comma to be included in your string, use %[^,] instead:

fscanf(finput, "%5[^,], %d, %d", x, &y, &z)
//                ^^^^
//                 ||
// This means "read characters until you hit a comma

Note that I added 5 to limit the length of the string being read to six chars.

Finally, to see if the fscanf returned a proper number of items, get its return value, and check if it's equal to the number of items that you expected:

int count = fscanf(finput, "%5[^,], %d, %d", x, &y, &z);
if (count == 3) {
    // All three items are there
} else {
    // We did not get enough items
}

Outras dicas

x is an array of exactly 6 characters. You cannot store more than that on static-allocated array.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top