由双引号 "#" 分隔的输入数据会使问题稍微复杂化。您使用scanf 阅读的尝试注定会失败。您的scanf 格式字符串"[%d,%d]\n" 不会读取/丢弃行尾的'\n'。事实上,它根本不匹配'\n'。 scanf 不解释控制字符,所以格式字符串中的 '\n' 正在寻找的是一个文字 'n' 在两次转换发生后导致 input-failure。 p>
你有两个选择:
- 从格式字符串中删除
'\n',继续使用scanf(不推荐),然后手动读取/丢弃该行中的所有剩余字符,直到达到'\n'(使用getchar() 或@987654334 @);或
- 使用
fgets() 或POSIX getline() 等面向行的 输入函数将每一行读入缓冲区,以确保每次读取完整的数据行,然后解析您需要的信息从缓冲区使用sscanf(首选方法)。
采用上述首选方法,您可以执行以下操作:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer for each line */
int x, y, n = 0; /* coordinates & counter */
printf ("set[%d]:", n++); /* initial set[]: label */
while (fgets (buf, MAXC, stdin)) { /* read each line */
if (strncmp (buf, "\"#\"", 3) == 0) /* line starts with "#"? */
printf ("\nset[%d]:", n++); /* output new set[]: label */
else if (sscanf (buf, " [%d,%d]", &x, &y) == 2) /* 2 conversions? */
printf (" %d,%d", x, y); /* output coordinates */
}
putchar ('\n'); /* tidy up with newline */
return 0;
}
(注意:如果您的文件只包含# 而不是"#",您可以简单地检查缓冲区中的第一个字符而不是使用strncmp)
输入文件示例
$ cat dat/coordgroups.txt
[0,0]
[1,1]
[2,2]
"#"
[1,3]
[3,6]
[9,8]
使用/输出示例
$ ./bin/readcoords < dat/coordgroups.txt
set[0]: 0,0 1,1 2,2
set[1]: 1,3 3,6 9,8
检查一下,如果您还有其他问题,请告诉我。