#include <stdio.h>
#include <string.h>
int main()
{
char cipher[5][5] = {
{'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i', 'k'},
{'l', 'm', 'n', 'o', 'p'},
{'q', 'r', 's', 't', 'u'},
{'v', 'w', 'x', 'y', 'z'}
};
char cm;
char *original;
char *portion;
printf("Enter ciphered message: ");
scanf("%s", &cm);
original = strdup(&cm);
portion = strtok(original, "-");
while (portion != NULL){
int i = portion[0]-'0';
int j = portion[1]-'0';
printf("%c", cipher[i][j]);
portion = strtok(NULL, "-");
}
return 0;
}
你好,我是一名新的計算機科學專業的學生,??我已經遇到了問題。我正在撰寫一個 polybius 密碼,但我似乎無法正確保存用戶輸入以在 strdup 中使用
輸入即:00-11-22-33-44 我應該收到“agntz”,但我無法列印。我是新來的,所以如果我沒有正確格式化我的問題,我深表歉意。
uj5u.com熱心網友回復:
主要問題是您char cm是單個字符,但您想讀取字串char *cm。如果您scanf()支持可選m字符,那么最簡單的選擇是讓它為您分配字串:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <string.h>
int main(void) {
char cipher[5][5] = {
{'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i', 'k'},
{'l', 'm', 'n', 'o', 'p'},
{'q', 'r', 's', 't', 'u'},
{'v', 'w', 'x', 'y', 'z'}
};
char *cm;
char *original;
char *portion;
printf("Enter ciphered message: ");
scanf("%ms", &cm);
original = strdup(cm);
portion = strtok(original, "-");
while (portion != NULL){
int i = portion[0]-'0';
int j = portion[1]-'0';
printf("%c", cipher[i][j]);
portion = strtok(NULL, "-");
}
printf("\n");
}
你現在得到了預期的輸出:
Enter ciphered message: 00-11-22-33-44
agntz
最好檢查 part[0] 和 part[1] 確實是數字(例如通過使用isdigit()),以避免越界訪問cipher. strlen(portion) == 2還要檢查您在 ( )部分中是否只有兩位數。
j是故意在密碼中丟失嗎?
您可以按照以下方式重構上述內容:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <string.h>
int main(void) {
char cipher[] = "abcdefghiklmnopqrstuvwxyz";
char *cm;
printf("Enter ciphered message: ");
scanf("%ms", &cm);
for(char *portion = strtok(cm, "-"); portion; portion = strtok(NULL, "-")) {
int i = portion[0]-'0';
int j = portion[1]-'0';
printf("%c", cipher[5*i j]);
}
printf("\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/531003.html
上一篇:如何使用陣列資料驗證值?
下一篇:從物件值替換陣列的相似項
