2016-11-29 38 views
0

文字を取り、シーザー暗号を使用して1つの値をbにシフトするプログラムを作成したい。これを行うには文字列を使用する必要があります。C言語 - シーザー暗号化プログラム

私の問題は私のプログラムは文字列にユーザーの入力を取らないことです。 (私はguy [10]をscanfに入れようとしましたが、プログラムがクラッシュするだけでしたので、間違った人をそこに置いてプログラムがコンパイルされる可能性があります)。それは名前は、このコンテキスト内のポインタとして扱われます、我々はそれへのポインタを取得する必要はありませんので、guyとして

scanf("%s",&guy); 

が配列である:

#include <stdio.h> 


int main(){ 
int i=0; //setting the individual slot number for the array-- later used in the while loop 
char guy[10]; 
printf("Enter Plain Text:"); 
scanf("%s",&guy); //takes user's input-- such as "abc" and puts it into its respective slot in the array guy[10] r-right? 

while (guy[10] != '\0'){ //while loop that runs until it reaches the end of the string 
    if ((guy[i]) >= 'A' && (guy[i]<= 'Z')){ //moves capital letter values up 1 
     guy[i]=guy[i]++; //makes the current "slot" number go up 1 value. Example: a = 97 + 1 -> b = 98 
     } 
    if ((guy[i]) >= 'a' && (guy[i]) <= 'z'){// moves lower case letter values up 1 
     guy[i]=guy[i]++; 
    } 
    i++; //moves the array's interval up to the next "slot" 

} 
printf("Encrypted text is: %s",guy); 
} 
+0

をシーザー暗号を合理的にC言語で実装するための多くの方法であり、このサイトの検索ボックスにある '' Caesar''は、100以上のものを生成します。あなたのコードについて。 'guy [10]'ではなく 'guy [i]'があなたのwhile-condition式に含まれているはずです。 '&guy'ではなく' guy'が 'scanf'に渡されるパラメータでなければなりません。 – WhozCraig

+0

これは本当ですが、どれもC言語にも深くは触れていません –

答えて

0

あなたの最初の問題は、この行です。単純に実行します。

(void) scanf("%s", guy); 

はあなたの第二の問題は、この行です:

while (guy[10] != '\0') 

WhozCraigがint彼のコメントに述べたように - これはインデックスiを使用すべきではなく、10

第三の問題は、このことですが声明はほとんど意味をなさない:

guy[i]=guy[i]++; 

リア

guy[i] = guy[i] + 1; 
guy[i]++; 
guy[i] += 1; 

第4の問題は、ラップアラウンドを処理していないことです。例えば。あなたのコードに「Z」がマップされるのは何ですか?それは "A"の代わりに "["として出てくるようです。

第5の問題は、入力サイズが無制限のためguyの配列がオーバーフローする可能性があることです。最後の「\ 0」のための部屋で9文字まで入力を制限するには

scanf("%9s", guy); 

guy[10]については、我々のような何かをする必要があります。それはより安全だと私たちはscanf()のパース力を必要としないようfgets()を使用すると、このような状況では、より良い選択である:

fgets(guy, 10, stdin); 

ここでは、これらの5つの問題に対処リワークだ:そこに、FYI

#include <stdio.h> 

int main() { 
    char text[10]; 

    printf("Enter Plain Text: "); 
    (void) fgets(text, 10, stdin); // takes user's input -- such as "abc" and put it into its respective slots in the array 

    int i = 0; // slot index for the array 

    while (text[i] != '\0') { // loop until reach end of string 

     if (text[i] >= 'A' && text[i] <= 'Z') { // move capital letter values up 1 
      // make the letter go up 1 modulo 26. Example: A = 65 + 1 -> B = 66; Z = 90 + 1 -> A = 65 
      text[i] = ((text[i] - 'A' + 1) % ('Z' - 'A' + 1)) + 'A'; 
     } else if (text[i] >= 'a' && text[i] <= 'z') { // move lower case letter values up 1 
      text[i] = ((text[i] - 'a' + 1) % ('z' - 'a' + 1)) + 'a'; 
     } 

     i++; // move the array's index up to the next "slot" 
    } 

    printf("Encrypted text is: %s\n", text); 
} 
関連する問題