Paul Joshua Beldia Paul Joshua Beldia - 1 month ago 7
C Question

How do you get an INTEGER in a textfile mixed with Strings and Integer?

I'm trying to get an

int
value from a text file.
This is my current read file algorithm:

if (q)
{
while ((ch = fgetc(q)) != EOF)
{
if(ch == )
printf("%c",ch);
}
}
else
{
printf("Failed to open the file\n");
}


Inside my text-file:

Occupant's Name: qwe qwe
Room Number: 1
Occupant's Category: Superior Double

Occupant's Name: h j
Room Number: 1
Occupant's Category: Superior Double

Occupant's Name: h j
Room Number: 1
Occupant's Category: Superior Double


I would like to get every room number.

Answer

Consider using fgets to read each line and sscanf to parse the line. This sscanf will fail on the lines that do not start with "Room Number:".

char line[100] = "";
int room = 0;
if (q) 
{
    while (( fgets ( line, sizeof line, q)))
    {
        if( ( sscanf ( line, "Room Number:%d", &room)) == 1) {
            printf("room number is %d\n", room);
        }
    }
}
else
{
    printf("Failed to open the file\n");
}
Comments