【发布时间】:2022-01-22 08:29:20
【问题描述】:
我需要创建一个程序来逐行读取文件并在每一行扫描一些数据。 例如在一行中:
# 2 (x1,y1)(x2,y2)
我需要 x1,y1 和 x2,y2 我的代码是
char firstCharacter;
char line[100];
scanf("%c",&firstCharacter);
while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n')){
if(firstCharacter == '#'){
int nu_deadend;
sscanf(line,"%d",&nu_deadend);
for (int i = 0; i < nu_deadend; i++) {
int x,y;
sscanf(line,"(%d,%d)",&x,&y);
printf("x: %d y: %d\n",x,y);
}
}
}
return 0;
但来自输入:
# 2 (2,3)(3,4)
它输出:
x:0 y:0
x:0 y:0
预期输出:
x:2 y:3
x:3 y:4
我做错了什么?
【问题讨论】:
-
请说明您的代码忽略的scanf的所有返回值。
-
与
scanf不同,sscanf会从它给定的缓冲区开始。因此,您可能需要使用(例如)char *cp = line;,然后使用并前进cp以指向下一个令牌。sscanf不适合这个。最好使用fgets、cp和strtok并将strtok的返回值传递给sscanf此外,您永远不会为第二行重置firstCharacter(即我假设每一行都以@987654338 开头@)