[英]I'm having trouble scanning hex values into an array in C
I am trying to scan a .dat file containing hex values into an array using fscanf(). 我试图使用fscanf()将包含十六进制值的.dat文件扫描到一个数组中。 My program successfully scans the file and puts values into the array, but when I print them back out to console, the values are drastically different.
我的程序成功扫描文件并将值放入数组中,但当我将它们打印回控制台时,值会大不相同。 The following code is my function that opens the file and scans it.
以下代码是我打开文件并进行扫描的功能。 I'm using a test.txt file right now that has the values "1 2 3 4 5 6 7 8 9 abcdef" in it.
我正在使用一个test.txt文件,其中包含值“1 2 3 4 5 6 7 8 9 abcdef”。 When I run the program what prints in the console is 5 hex values that change after each run followed by "0 ffffffff 0 0 0".
当我运行程序时,在控制台中打印的是5个十六进制值,每次运行后更改后跟“0 ffffffff 0 0 0”。
void sim(int bytes, int lines, int sets, int policy){
int i = 0;
int total_Misses = 0;
int total_References = 0;
FILE *f1 = fopen("test.txt", "r");
if (f1 == NULL){
printf("File failed to open");
exit(0);
}
unsigned int a[10];
while (i < 10){
fscanf(f1, "%x", &a[i]);
printf("%x ", a[i]);
i++;
}
}
The code looks OK and all comments point to a problem with the input. 代码看起来没问题,所有注释都指向输入问题。 I suggest you adapt the code to the following to catch errors:
我建议您调整以下代码以捕获错误:
while (i < 10){
if (fscanf(f1, "%x", &a[i])==1) {
printf("%x ", a[i]);
i++;
}
else printf ("Error reading field %d\n", i);
}
Ps: a[10]
is an automatic variable and not initialized. Ps:
a[10]
是一个自动变量而没有初始化。 Hence not reading a value for the array entry will print the uninitialzed garbage value you are experiencing. 因此,不读取数组条目的值将打印您正在经历的未初始化的垃圾值。
Pps: I often see scanf
gurus add a space before the %
sign to skip leading white space. Pps:我经常看到
scanf
专家在%
符号前添加一个空格以跳过前导空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.