如何在与字符串和整数混合的文本文件中获得INTEGER?

时间:2016-10-16 15:54:52

标签: c

我试图从文本文件中获取int值。 这是我目前的读取文件算法:

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

在我的文字档案中:

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

我想获得每个房间号码。

1 个答案:

答案 0 :(得分:0)

考虑使用fgets读取每一行,并使用sscanf来解析该行。这个sscanf将在不以“房间号:”开头的行上失败。

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");
}