简体   繁体   English

如何在混合了Strings和Integer的文本文件中获得INTEGER?

[英]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. 我正在尝试从文本文件中获取一个int值。 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. 我想获得每个房间号。

Consider using fgets to read each line and sscanf to parse the line. 考虑使用fgets读取每一行,并使用sscanf解析该行。 This sscanf will fail on the lines that do not start with "Room Number:". 该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 %d\n", room);
        }
    }
}
else
{
    printf("Failed to open the file\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM