你在一个混合了字符串和整数的文本文件中得到一个INTEGER



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

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

在我的文本文件中:

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

我想知道每个房间的号码。

考虑使用fgets读取每行并使用sscanf解析该行。此sscanf将在不以"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 %dn", room);
        }
    }
}
else
{
    printf("Failed to open the filen");
}

相关内容

最新更新