【发布时间】:2015-01-26 15:26:13
【问题描述】:
我有一个程序,它在 for 循环中多次确定 int 的值 fc1,并使用 fprintf 将其输出到文件。
for (i=0; i<80; i++)
{
fc1 = somefunction(); // this function determines if fc is 0 or 1
// printing fc1 to stdout
printf("%d\n", fc1);
// printing output to file
fprintf(out, "%d ", fc1);
}
每当我运行循环 80 次或更少时,文件输出就像预期的那样:
1 0 1 0 1 1 0 0 0 0 1 0 1 1 1 1 0 0 0 1 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 0 0 1 0 1 0 1 0 1 1 0 1 1 0 0 0 1 0 1 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 0 0
但是,一旦我循环它 81 次或更多,文件输出就是垃圾..
‱‰‱‰‱‱‰‰‰‰‱‰‱‱‱‱‰‰‰‱‱‰‱‱‱‰‱‰‰‱‱‱‰‰‱‰‰‱‰‱‰‱‰‱‱‰‱‱‰‰‰‱‰‱‰‱‰‰‱‱‰‰‱‰‰‰‰‰‰‱‱‱‰‱‰‱‰‱‰‰‱
即使我打印的是整数,它也会以某种方式最终输出 U+2030 和 U+2031。
当我尝试时
fprintf(out, "%d", fc1);
fputc(' ', out); // i changed the fprintf to fprintf the int and fputc the space
什么也没有改变,这个问题仍然会发生,但是当我这样做时
fprintf(out, "%d", fc1);
fputc(' ', out);
fputc(' ', out);
不知何故,它起作用了!并且输出将有2个空格,
1 0 1 0 1 1 0 0 0 0 1 0 1 1 1 1 0 0 0 1 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 0 0 1 0 1 0 1 0 1 1 0 1 1 0 0 0 1 0 1 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 0 0 1
谁能告诉我我使用 fprintf 有什么问题?
一些附加信息
- 所有变量都是整数
- 文件指针设置正确
- fc1 每次循环运行时肯定有 1 或 0(因为我将值打印到标准输出,我可以看到它的 0 或 1)
- GNU GCC 编译器,Windows 7 上的 MingW CodeBlocks 12.11
编辑:
这里是 somefunction()
int fc(int a, int b, int c, int d, int e)
{
int bits = a*10000+b*1000+c*100+d*10+e;
switch(bits)
{
case 0:
case 1:
case 100:
case 101:
case 111:
case 1000:
case 1001:
case 1110:
case 1111:
case 10000:
case 10001:
case 10010:
case 10100:
case 10110:
case 11010:
case 11110:
return 1;
break;
default:
return 0;
break;
}
}
以及我打开文件指针的方式
FILE *out = fopen("out.txt", "w");
我在 windows 上用记事本打开输出文件
【问题讨论】:
-
发布
somefunction或者我们所能做的就是猜测。毫无疑问,您的循环中要么溢出了存储大小,要么溢出了数组。您可以使用 int 在2147483648 - 2147483647之间循环和打印%d的所有值,并且永远不会有任何问题,但是一旦您导致 int 超过above/below,您就会溢出并误入undefined behavior除非您处理它。 -
您能说明如何打开您的
out文件吗?你用什么标志?另外,您使用什么软件来读取out文件?是否支持 UTF-8 编码? -
如果您使用 notepad++ 或其他工具打开该文件,他们可能会推断出导致您出现问题的编码。尝试强制在 iso-8859-1 或 ASCII 中查看...
-
对大家来说,我现在知道这可能只是一个编码问题,但是你们知道为什么它在循环 80 次后特别搞砸了吗?
-
@Christopher:不具体,使用的函数
IsTextUnicode是一个启发式黑盒。