So I've tried nearly all solutions for similar questions and neither of them worked. I have a string which looks like the following:
AAAA BBBBBBBBBBBB CCCCCCC 15
%s %s %s %d
I've so far tried it like:
sscanf(str, "%s %s %s %d", ...);
It did not work the first %s ate the ' ' also and all went wrong. After that i tried like:
sscanf(str, "%6[^ ] %30[^ ] %8[^ ] %d[^\n]", ...);
The same thing happens. How can i split the parts of this string with sscanf?
Edit: The result should go in a struct. The current code looks like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct sor {
char npkod[6];
char nev[30];
char tkod[8];
int jegy;
} SOR;
double work(char* fnev, char* tkod)
{
FILE * fp;
char aktualis_sor[127] = { 0 };
SOR beolvasott_sor;
double atlag = 0.0;
int ossz = 0;
int db = 0;
fp = fopen(fnev, "rb");
if(fp == NULL)
{
printf("Fajl nem talalhato.\n");
return -1;
}
while(fgets(aktualis_sor, 127, fp))
{
sscanf(aktualis_sor, "%6[^ ] %30[^ ] %8[^ ] %d", beolvasott_sor.npkod, beolvasott_sor.nev, beolvasott_sor.tkod, &beolvasott_sor.jegy);
printf("%s %s %s %d\n\n\n", beolvasott_sor.npkod, beolvasott_sor.nev, beolvasott_sor.tkod, beolvasott_sor.jegy);
if(strcmp(beolvasott_sor.tkod, tkod) == 0)
{
ossz += beolvasott_sor.jegy;
++db;
}
}
fclose(fp);
atlag = (double)ossz / (double)db;
return atlag;
}
int main(void)
{
printf("Atlag: %f\n", work("tan.txt", "INDK1010"));
return 0;
}
And here's the actual problem: Original: AAA111 Harminckarakteresnevaaaaaaaaaa INDK1010 5
printf after sscanf: AAA111HarminckarakteresnevaaaaaaaaaaINDK1010♣ HarminckarakteresnevaaaaaaaaaaINDK1010♣ INDK1010♣ 5