![](/img/trans.png)
[英]Core Dump (Segmentation fault) in this little encryption program I wrote in C for cs50
[英]CS50 / BEGINNER - Segmentation fault in nested for loop in C
我正在嘗試編寫代碼,該代碼將從純文本字符串輸入中獲取每個數字,如果它是一個字母,則 output 是一個不同的字母,由替換鍵(26 個字母鍵)定義。
換句話說,如果字母表是“abcd”並且提供的鍵是“hjkl”,那么輸入“bad”將是 output“jhl”。
// Regular alphabet is to be used as comparison base for key indexes //
string alphabet = "abcdefghijklmnopqrstuvwxyz";
// Prompt user for input and assign it to plaintext variable //
string plaintext = get_string("plaintext: ");
非字母應按原樣打印。
我的想法是通過字母表中的每個索引循環輸入數字以查找相應的字母,如果找到,則從字符串中打印相同的索引字符。 (令人困惑,我認為)
然而,這個循環在我運行它時會返回一個段錯誤,但在調試時不會:
// Loop will iterate through every ith digit in plaintext and operate the cipher //
for (int i = 0; plaintext[i] != '\0'; i++) {
// Storing plaintext digit in n and converting char to string //
char n[2] = "";
n[0] = plaintext[i];
n[1] = '\0';
// If digit is alphabetic, operate cipher case-sensitive; if not, print as-is //
if (isalpha(n) != 0) {
for (int k = 0; alphabet[k] != '\0'; k++) {
char j[2] = "";
j[0] = alphabet[k];
j[1] = '\0';
if (n[0] == j[0] || n[0] == toupper(j[0])) {
if (islower(n) != 0) {
printf("%c", key[k]);
break;
} else {
printf("%c", key[k] + 32);
break;
}
}
}
} else {
printf("%c", (char) n);
}
}
怎么了? 我在網上尋求幫助,但大多數資源對初學者不太友好。
您的代碼似乎可以正常工作,除了一個錯誤:程序在
isalpha(n)
因為你聲明
char n[2]
參數有一個char*
類型的指針。 但是islower
只接受一個int
參數,所以直接寫成
isalpha(n[0])
islower
一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.