【发布时间】:2024-01-09 00:00:01
【问题描述】:
我正在尝试实施一个项目来读取十六进制数字并对其进行排序。当我在代码中硬写输入时,代码与我一起正确工作,但是当我修改代码以从文本文件中获取输入时,我得到了不正确的结果,当我调试代码时,我发现令牌没有得到所有的值,我不知道为什么。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *in_file = fopen("input.txt", "r");
FILE *out_file = fopen("output.txt", "w");
int bufferLength = 255;
char buffer[bufferLength];
if (in_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
char input[] = {};
fgets(input, bufferLength, in_file);
int decimal[1000] = {0};
char * token = strtok(input, " ");
int n = (int) strtol(token, NULL, 16);
decimal[0] = n;
printf("N is : %d , token is : %s \n", n, token);
int no = 0;
while(token != NULL) {
token = strtok(NULL, " ");
int n = (int) strtol(token, NULL, 16);
decimal[no+1] = n;
no++;
printf("N is : %d , token is : %s \n", n, token);
}
int temp = 0;
//Sort the array
for (int i = 0; i < no; i++) {
if (decimal[i] == 0){
break;
}
for (int j = i+1; j < no; j++) {
if(decimal[i] > decimal[j]) {
temp = decimal[i];
decimal[i] = decimal[j];
decimal[j] = temp;
}
}
}
//Print elements
for (int j = 0; j < no; j++){
fprintf(out_file,"%X ", decimal[j]);
}
fclose(in_file);
fclose(out_file);
return 0;
}
输入是:10 A B 1,但是在调试代码时我得到了以下结果:
N is : 16 , token is : 10
N is : 10 , token is : A
N is : 0 , token is : (null)
【问题讨论】:
-
请edit 并显示格式正确的最小版本的 input.txt 文件。以及预期与实际输出。
-
char input[] = {};input数组的固定长度为零,这没有意义。你想要char input[bufferLength] = {0};。不过可能还有其他问题。 -
printf("Error! Could not open file\n");是无用错误消息的典型示例。试试perror("input.txt");