Question

I have little code problem..Someone have any idea what could be wrong?

my code:

FILE *tiedosto;
char tiedostonimi[] = "input.txt";
tiedosto = fopen (tiedostonimi, "r");
char luokka, kaupunki[4];
int kuutio, vuosi, kuukausi, paiva;

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, &kaupunki, &vuosi, &kuukausi, &paiva);
printf("%d %c %s %d %d %d , kuutio, luokka, kaupunki, vuosi, kuukausi, paiva);

line inside txt file:

22&energialuokka=A&kaupunki=ei&Vuosi=2010&Kuukausi=02&pva=22

("22" "A" "ei" "2010" "02" "22" are not permanent values.. given via website form and saved into text file)

Current

OUTPUT IS:

22 u ei&Vuosi=2010&Kuukausi=02&pva=22 831192666 0 -163754450
Was it helpful?

Solution

The problem is that when scanning for a string, the scanf family of function will scan until a whitespace (or end of file, whichever happens first). You can't really use pattern-matching when scanning for a string. You can verify this quite simply by checking the return value of fscanf, in your case it should be 3 (since it scans the integer, a character and then the rest as a single string).

Incidentally this will of course lead to undefined behavior as you overwrite the array allocated for the string by quite a margin, as well as you printing the values of uninitialized local variables.

Instead it might be better to tokenize the input (hint: see the strtok function), to first split it on the ampersand '&', and except the first value then split the other on the equality character '='. Then check each "key" to know what value to set.

OTHER TIPS

When scanning in a C-"string" do not use the address-of operator (&).

So this line:

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, &kaupunki, &vuosi, &kuukausi, &paiva);

should be like this:

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, kaupunki, &vuosi, &kuukausi, &paiva);

The background to this is, that if using the array variable without index operator it (already) decays to the pointer to (the address of) its first element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top