我有一个 C 程序,当我进入 while 循环时遇到错误。
我初始化一个变量(fragmentcount)并使用 fscanf 写入它并为其分配值 4(这有效)
int fragmentCount;
if ((fscanf(fp, "%i", &fragmentCount)) == 1) {
...
}
但是,当我尝试在下面的 while 循环中访问它时,fragmentCount = 0
while ((fscanf(fp, "%[#]", discards)) != EOF) {
printf(fragmentCount); // <- pseudocode
}
为了进行一个简短的实验,我尝试去掉 fscanf 作为 while 循环的条件测试,并且fragmentCount 是正确的值 (4)。
为什么会这样呢?我怎样才能避免这种情况?
最佳答案
如何声明discards
? fscanf 读取的数据可能超出了 discards
的空间,这可能会覆盖其他变量的值。
使用不带字段宽度的“%[”格式是一个坏主意 - 它 leaves your program open to buffer overflow errors .
关于C:fscanf 删除整数变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3869491/