我正在读取列表中每一对的键和值,忽略空格并尝试打印它。我的文件包含以下数据:
(2, 50) (4, 30) (9, 30) (10, 400) (-5, -40)
(7, 20) (19, 200) (20, 50) (-18, -200) (-2, 29)
(2, 67) (4, 35) (9, 45) (-18, 100)
我正在尝试一一获取括号内的整数。例如。
m=2
n=50
m=4
n=30
我尝试从文件中读取数据直到文件结束。扫描并打印 m 和 n 值。
int m,n;
FILE* file = fopen("File1.txt", "r"); // open a file
while (!feof (file))
{
fscanf (file, "(%d, %d)", &m, &n);
printf("m is %d:", m);
printf("n is %d:", n);
}
//close the file after opening
fclose (file);
运行代码时构建成功,而
m is 2:n is 50:m is 2:n is 50:m is 2:n is 50:m is 2:n is 50:m is 2:n is 50:m is 2:n is 50:m is 2:
无休止地打印而不是从文件中读取整数。
请帮忙。
最佳答案
我看到的错误:首先是误用了feof
,第二是输入卡在了第二个'('
,其中实际上有一个空格输入数据。您可以通过在格式说明符中添加空格来过滤掉(空白)空格。此外,您应该始终检查文件是否打开。
#include <stdio.h>
int main()
{
int m,n;
FILE* file = fopen("File1.txt", "r");
if(file == NULL) {
return 1; // error checking
}
while (fscanf (file, " (%d,%d)", &m, &n) == 2) // check for number of conversions
// space added here ^ ^ the space here was unnecessary
{
printf("m=%d, n=%d\n", m, n);
}
fclose(file);
return 0;
}
程序输出:
m=2, n=50 m=4, n=30 m=9, n=30 m=10, n=400 m=-5, n=-40 m=7, n=20 m=19, n=200 m=20, n=50 m=-18, n=-200 m=-2, n=29 m=2, n=67 m=4, n=35 m=9, n=45 m=-18, n=100
Because feof
detects if there was a previous attempt to read beyond the end of the file, which you don't do, the end condition was never met.
Edit: answering the comment below, the format string can be made to tolerate additional whitespace anywhere in the input, by adding a space before every specifier that does not automatically filter whitespace. Like this:
fscanf (file, " (%d ,%d )", &m, &n)
格式字符串中每个括号和逗号前面现在有一个空格。每个 %d
之前不需要有空格,因为该格式规范会自动过滤掉前导空格。这对于随机间隔的输入(例如
" ( 4 , 30 ) "
关于c - 有没有办法在C中读取括号内以逗号分隔的2个整数,忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55373268/