2017-01-21 4 views
-1

Mein Programm funktioniert nur für Großbuchstaben und ich kann das Problem nicht herausfinden. Alles scheint in Ordnung zu sein, aber das ist es tatsächlich nicht. Dies ist übrigens eine Aufgabe des CS50-Kurses (Woche 2). Hier ist mein Code:Die Caesar-Chiffre funktioniert nur für Großbuchstaben (CS50)

#include <stdio.h> 
#include "cs50.h" 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

int main(int argc, string argv[]) 
{ /* Main should take only one parameter (except program execution, of course) */ 
    if (argc != 2) 
    return 1; 

    string text = GetString(); // text to encrypt 

    int i, l = strlen(text); 
    int k = atoi(argv[1]); // shift value (key) 
    /* Shift value should be less or equal to 26 */ 
    if (k > 26) 
    k = k % 26; 

    for (i = 0; i < l; i++) 
    { /* Making sure the character to encrypt is a letter (from English alphabet) */ 
    if ((islower(text[i])) || (isupper(text[i]))) 
    { 
     if ((islower(text[i])) && ((text[i] + k) > 'z')) 
     text[i] = ('a' + text[i] + k - 'z' - 1); 
     if ((isupper(text[i])) && ((text[i] + k) > 'Z')) 
     text[i] = ('A' + text[i] + k - 'Z' - 1); 
     else 
     text[i] = text[i] + k; 
    } 
    printf("%c", text[i]); 
    } 
    printf("\n"); 

    return 0; 
} 

Ergebnis

caesar.exe 13 
HELLO WORLD hello world 
URYYB JBEYQ uryyk sknyq 
+0

kann man auf den ersten –

+0

Und dann die verschlüsselten Zeichen in Kleinbuchstaben verwenden 'toUpper' Funktion konvertieren:

if ((islower(text[i])) || (isupper(text[i]))) { if ((islower(text[i])) && ((text[i] + k) > 'z')) text[i] = ('a' + text[i] + k - 'z' - 1); if ((isupper(text[i])) && ((text[i] + k) > 'Z')) text[i] = ('A' + text[i] + k - 'Z' - 1); else text[i] = text[i] + k; } 

Kann zu reduzieren? Natürlich wird es funktionieren, aber ich möchte herausfinden, warum mein Programm nicht funktioniert =) – PoorProgrammer

+0

Die Logik in Ihren 'if' Anweisungen ist ein bisschen seltsam. Welche Buchstaben sind größer als 'z'? Sie könnten mehr Variablen verwenden, um Ihren Code zu vereinfachen. Du solltest "toupper" oder "tolower" nicht mehr als einmal pro Charakter aufrufen müssen. –

Antwort

2

Dieser ganze Block;

if (islower(text[i]) || isupper(text[i])) 
{ 
    int base = islower(text[i]) ? 'a' : 'A'; 
    int ord = text[i] - base; // normalize text[i] to be between [0-25] 
    ord = (ord + k) % 26;  // rotate 
    text[i] = base + ord;  // convert back to alphabet value 
} 
+0

Eine kurze Anmerkung: Es könnte hier ein Fehler sein, wenn 'k' negativ und' (ord + k) <0' ist. Normalisieren Sie einfach k zu einer positiven Zahl, bevor Sie den Wert eingeben Schleife. – selbie