test.c 扫描 file.txt 并打印给定 ID 的名称。
我想向 file.txt 添加第三列
我还想问:
%99s
和 == 2
的含义是什么:
while (fscanf(fff, "%d %99s", &id, name) == 2) {
file.txt(添加新列)
1 name1 newcolumn1
2 name2 newcolumn2
3 name3 newcolumn3
修改 test.c 以使用第三列(添加 char name2[100];并克隆 %99s)
结果:不工作。 (编译:好的。但输出为空(什么也没有))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main() {
char name[100];
char name2[100];
FILE *fff;
int found = 0;
int id;
fff = fopen("/file.txt", "r");
while (fscanf(fff, "%d %99s %99s", &id, name, name2) == 2) {
if (id == 2) {
printf("%s\n", name2);
found = 1;
break;
}
}
fclose(fff);
return 0;
}
最佳答案
%99s
表示程序只能接受 name 和 name2 中最多 99 个字符。
现在 fscanf 返回一个 int 值,表示接受的输入数量并放入变量中。因此 fscanf(fff, "%d %99s %99s", &id, name) == 2
总是错误的,因为接受了 3 个输入。
fscanf 条件只是一个需要小心的安全措施(常见的 c 习惯用法)。
现在正确的程序是:
#include <stdio.h>
int main(void)
{
char name[100];
char name2[100];
FILE *fff;
int found = 0;
int id;
fff = fopen("/file.txt", "r");
if (fff == NULL)
return -1;
while ( fscanf(fff, "%d %99s %99s ", &id, name, name2) == 3 )
{
if (id == 2)
{
printf("%s\n", name2);
found = 1;
break;
}
}
fclose(fff);
return 0;
}
关于c - 如何将 "%99s "克隆到 : fscanf(file, "%d %99s", &id, name) == 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44670035/