【发布时间】:2018-11-07 19:51:36
【问题描述】:
当我编写简单的代码将简单的字母序列编码为字节并再次解码时,我遇到了解码问题。一切都在完成我想要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;
}
【问题讨论】:
-
这是 C 还是 C++?请不要标记两种不同的语言。而在 C 中,字符串必须以空值结尾。最后一个字符必须是
\0。 -
@Ron 代码看起来像 C,而不是 C++
-
能否提供样例输入输出?
-
你会想看看Why is while ( !feof (file) ) always wrong?。 (这解释了你的额外角色)