参见英文答案 How do I print a non-null-terminated string using printf?2个 当我编写简单的代码来将简单的字母序列编码为字节并再次解码时,我遇到了解码问题.一切都在完成我想要有4个字符的序列
当我编写简单的代码来将简单的字母序列编码为字节并再次解码时,我遇到了解码问题.一切都在完成我想要有4个字符的序列,但它也包括最后的字节.这是我的代码:
char* B2T(int num) {
unsigned char temp;
char res[4];
int sw[] = { 6,4,2,0 };
char tab[4] = { 'A', 'C', 'G', 'T' };
int i = 0;
for (int i = 0; i < 4; i++) {
res[i] = tab[(num >> sw[i]) & 3];
}
printf_s("%s\n", res); //!!!!!!problem here!!!!!!!!
return res;
}
int main() {
FILE *I, *O;
char tab[5], opt;
int res, i, temp;
bool work = true;
while (work) {
printf_s("\nChoose option: decode or encode (d/e): ");
scanf_s("%c", &opt);
switch (opt) {
case 'e':
fopen_s(&I, "DNA.txt", "r");
fscanf_s(I, "%s", &tab, 5);
fopen_s(&O, "result.bin", "a");
while (feof(I) == 0) {
res = T2B(tab);
printf_s("%X ", res);
fprintf_s(O, "%X ", res);
fscanf_s(I, "%s", &tab, 5);
};
fclose(I);
fclose(O);
break;
case 'd':
fopen_s(&I, "result.bin", "r");
fscanf_s(I, "%X", &temp);
while (feof(I)==0) {
char* ress = B2T(temp);
fscanf_s(I, "%X", &temp);
}
fclose(I);
break;
}
}
return 0;
}
您填充char res [4];,而不使用null终止它,这会导致未定义的行为,因为printf()期望空终止符号停止打印.
这样做:
char res[5]; res[4] = '\0';
此外,你应该专注于这一行:
while (feof(I) == 0)
它在循环中使用feof()来停止解析文件.这是一个已知问题,它解释了您的额外角色.请阅读Why is “while ( !feof (file) )” always wrong?
PS:通常,C库的所有函数都希望字符串以空值终止,因此强烈建议将所有字符串以空值终止.
