gpt4 book ai didi

c - 如何在混合有字符串和整数的文本文件中获取整数?

转载 作者:行者123 更新时间:2023-11-30 16:56:01 25 4
gpt4 key购买 nike

我正在尝试从文本文件中获取 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

我想知道每个房间号。

最佳答案

考虑使用 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 %d\n", room);
}
}
}
else
{
printf("Failed to open the file\n");
}

关于c - 如何在混合有字符串和整数的文本文件中获取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com