![](/img/trans.png)
[英]cs50 pset2:substitution. My code is not working for the letters 'o' and 'z'
[英]CS50 pset2 substitution
挑戰在於創建一個程序,您可以在其中輸入一個 26 字符長的字符串,它應該基本上替換字母表。 因此,例如,如果您將密鑰設置為“qwertyuiopasdfghjklzxcvbnm”,它將使用 q 代表 a,w 代表 b,e 代表 c,r 代表 d 等。然后您輸入一個作為您的消息的字符串,它會將明文轉換為密碼
到目前為止,在課程中我們還沒有涉及指針,所以我想一個人應該能夠在不使用 * 或 & 引用指針的情況下完成這一挑戰。 相反,我們被告知使用允許我們使用“字符串”的庫,而該庫處理在后台為我們使用指針的技術工作。 不過,我對此有點困惑,因為我最初嘗試的代碼是這樣的:
{
if(isupper(plainText[i]))
{
cypherText[i] = key[plainText[i] - 'A'];
}
else if (islower(plainText[i]))
{
cypherText[i] = key[plainText[i] - 'a'];
}
}
printf("%s\n", cypherText);
但我收到以下錯誤:
error: incompatible integer to pointer conversion assigning to 'string' (aka 'char *') from 'char'; take the address with & [-Werror,-Wint-conversion]
cypherText[i] = key[plainText[i] - 'A'];
^ ~~~~~~~~~~~~~~~~~~~~~~~
&
error: incompatible integer to pointer conversion assigning to 'string' (aka 'char *') from 'char'; take the address with & [-Werror,-Wint-conversion]
cypherText[i] = key[plainText[i] - 'a'];
^ ~~~~~~~~~~~~~~~~~~~~~~~
&
error: format specifies type 'char *' but the argument has type 'string *' (aka 'char **') [-Werror,-Wformat]
printf("%s\n", cypherText);
所以我將代碼更改為以下
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string key;
do
{
key = get_string("Key:");
}
while(strlen(key) != 26);
string plainText = get_string("Text:");
string cypherText[strlen(plainText)];
for (int i = 0; plainText[i] != '\0'; i++)
{
if(isupper(plainText[i]))
{
cypherText[i] = &key[plainText[i] - 'A'];
}
else if (islower(plainText[i]))
{
cypherText[i] = &key[plainText[i] - 'a'];
}
}
printf("%s\n", *cypherText);
}
現在它可以編譯但不能按預期工作,而且我無法通過調試來識別該錯誤。 基本上,當我使用鍵“bcdefghijklmnopqrstuvwxyza”(字母左移一個字母)運行它,然后我使用“hello”之類的消息時,我會得到 output “ijklmnopqrstuvwxyza”,它以正確的字母開頭,但隨后繼續解析字母對我來說莫名其妙。 即使我只寫一個長字母的消息,密文也會打印為多個字符。
所以我的問題是:
我的假設是否正確,即有一種方法可以在不使用指針的情況下完成此挑戰,如果是這樣,我如何在不使用 & 或 * 的情況下更正這些錯誤消息?
當我使用 & 和 * 時,是什么導致了這種奇怪的尾隨字母行為?
謝謝你。
您正在string cypherText[strlen(plainText)];
中定義一個字符串數組。 ,因此最初的錯誤是由於嘗試將字符串(也稱為 char*)分配給字符串數組(又名 char**),因此:
error: format specifies type 'char *' but the argument has type 'string *' (aka 'char **') [-Werror,-Wformat]
printf("%s\n", cypherText);
當你這樣做的時候
if(isupper(plainText[i]))
{
cypherText[i] = &key[plainText[i] - 'A'];
}
else if (islower(plainText[i]))
{
cypherText[i] = &key[plainText[i] - 'a'];
}
您正在操縱指針 cypherText 指向的位置,您實際上是在分配 cypherText[0][0] 以從&key[plainText[i] - 'a']
開始,在您的測試用例中是字母 'i'。 i 的每個增量都會更改 cypherText 數組的行,因此 cypherText[1][0] 將指向字母“f”,但至關重要的是,它與分配給您的key
的 memory 相同。
當你printf("%s\n", *cypherText);
,您要求打印出一個字符串,而*cypherText
是您的字符串數組的開頭,因此程序會愉快地打印出您之前指定為與key
相同的第一個字符串,但從字母 'i' 開始反而。 它讀取這個字符串,直到到達 '\0' 並愉快地稱之為一天。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.