【发布时间】:2021-12-18 11:56:55
【问题描述】:
下面的代码应该允许用户输入两个字符串 s 和 t,一个结构数组和大小 数组作为参数,将 s 中的字符编码为 t,并通过引用调用将编码后的字符串 t 传递给调用者。 我不明白为什么我的函数 encodeChar 是错误的。我已经尝试过使用索引方法,它类似于正确的答案。但是当我输入
1
3
a
b
b
c
c
d
3
abcd
4
,输出为 abdd。我不明白我的错误在哪里。请让我解决我的误解。
#include <string.h>
typedef struct {
char source;
char code;
} Rule;
void createTable(Rule *table, int *size);
void printTable(Rule *table, int size);
void encodeChar(Rule *table, int size, char *s, char *t);
int main()
{
char s[80], t[80], dummychar, *p;
int size, choice;
Rule table[100];
printf("Select one of the following options:\n");
printf("1: createTable()\n");
printf("2: printTable()\n");
printf("3: encodeChar()\n");
printf("4: exit()\n");
do {
printf("Enter your choice: \n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("createTable(): \n");
createTable(table, &size);
break;
case 2:
printf("printTable(): \n");
printTable(table, size);
break;
case 3:
scanf("%c",&dummychar);
printf("Source string: \n");
fgets(s, 80, stdin);
if (p=strchr(s,'\n')) *p = '\0';
encodeChar(table,size,s,t);
printf("Encoded string: %s\n", t);
break;
default:
break;
}
} while (choice < 4);
return 0;
}
void printTable(Rule *table, int size)
{
int i;
for (i=0; i<size; i++)
{
printf("%d: %c->%c\n", i+1, table->source, table->code);
table++;
}
}
void createTable(Rule *table, int *size)
{
/*edit*/
/* Write your code here */
/*edit*/
/* Write your code here */
int i;
char dummy[80];
printf("Enter number of rules: \n");
scanf("%d", size); // dont careless here
for(i=0; i< *size; i++){
printf("Enter rule %d: \n", i+1);
fgets(dummy, 80,stdin); // why need to use this twice
printf("Enter source character: \n");
scanf("%c", &table[i].source);
fgets(dummy,80,stdin);// why
printf("Enter code character: \n ");
scanf("%c", &table[i].code);
}
/*end_edit*/
/*end_edit*/
}
void encodeChar(Rule *table, int size, char *s, char *t)
{
/*edit*/
/* Write your code here */// this is wrong
int i, j;
for(i = 0 ; s[i] != '\0'; i++){
for(j = 0; j < size; j++){
if(s[i] == table[j].source){
*t = table[j].code;
}
else{
*t = s[i];
}
}
t++;
}
*t = '\0';
/*edit*/
/* this is correct
int i;
while(*s!='\0'){
for(i = 0; i < size; i++){
if(*s != table[i].source)
*t = *s;
else
*t = table[i].code;
t++;
s++;
}
}
*t = '\0';
*/
}
【问题讨论】:
-
我看到的第一个区别是,在第二个版本中,您在内部循环中迭代
t,而在第一个版本中没有。 -
您是否需要有关如何调试此代码的建议,或者您只是希望有人为您修复它?如果您能努力将这个问题减少到minimal reproducible example,这将有所帮助,否则这个问题可能会被关闭。
标签: c loops pointers structure