I am having a small problem with fscanf
reading from a text file.
I have this small piece of code (C++):
struct tooted
{
char nimi[50];
int kogus;
float hind;
}toode[20];
int main()
{
FILE *kala;
kala = fopen("kala.txt", "r");
int i=0, n=0;
char buffer[200];
while(!feof(kala))
{
if(n<1)
{
fgets(buffer, 200, kala);
}
if(n>0)
{
fscanf(kala, "%s[^\t]%i[^\t]%f", toode[i].nimi, toode[i].kogus, toode[i].hind);
i++;
}
n++;
}
for(i=0; i<n-1; i++)
{
printf("Toode: %s\nKogus: %i\n Hind: %f\n\n", toode[i].nimi, toode[i].kogus, toode[i].hind);
}
return 0;
}
The fgets(buffer, 200, kala);
is just to start the fscanf
from the second row.
In the file kala.txt
I have 3 rows separated with [tab]. The first word is a string, the second an integer, and the third a float, like this:
product1 (tab) 4 (tab) 1.4
product2 (tab) 3 (tab) 2.3
It reads the words (and numbers) one by one using only the toode[i].nimi
so the outcome is:
Toode: product1
Kogus: 0
Hind: 0.0000
Toode: 4
Kogus: 0
Hind: 0.0000
etc.
Note also that product1
can be two words, but they are separated with a space not tab. I want it to read product1
as one string.
(I tried looking it up before asking, but I couldn't find the solution. Sorry if it's a repost.)
Thank you :)