下面的代碼應該允許用戶輸入兩個字串 s 和 t,一個結構陣列和陣列的大小作為引數,將 s 中的字符編碼為 t,并將編碼后的字串 t 通過 call by 傳遞給呼叫者參考。我不明白為什么我的函式 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';
*/
}
uj5u.com熱心網友回復:
這里一張紙和一支鉛筆就足夠了。
只需按照您的代碼進行abcd. 相關部分是
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';
我們走吧:
i是 0,s[i]是aj是 0,table[j].source是a:*t接收bj是 1,table[j].source是b:*t收到(回傳)a!...
只有最后一條規則可以應用于您的代碼...
一個簡單的解決方法是在應用規則以防止以下規則回滾更改時跳出回圈:
for(i = 0 ; s[i] != '\0'; i ){
for(j = 0; j < size; j ){
if(s[i] == table[j].source){
*t = table[j].code;
break; // do not examine other rules
}
else{
*t = s[i];
}
}
t ;
}
*t = '\0';
但是如果同一個字符被多個規則改變,這個代碼將使用第一個,而正確的代碼將使用最后一個,所以這會更一致:
for(i = 0 ; s[i] != '\0'; i ){
for(j = size-1; j >= 0; j--){ // examine rules in descending order
...
無論如何,這里仍然有可能的改進,所以你可以將它發布到 CodeReview 以獲得最佳實踐的建議......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347909.html
