2014-12-07 24 views
0

我已經爲一個任務編寫了這個簡單的程序,但是當我輸入我的文本時,輸出給了我符號而不是字符。任何幫助,將不勝感激。我不知道爲什麼我的輸出出現這種方式,但程序似乎編譯正常。也許它正在工作,我需要用數學做一個基礎測試,看看它是否正常運行。無論如何,如果任何人看到錯誤,非常感謝反饋。ASCII字符在簡單的C程序中搞砸了

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

string Crypto(string, int); // rotation 


int main(int argc, string argv[]) 
    { 
    int k = 0; 
    // error checing 
    if (argc == 0 || argc == 1 || argc > 2) 
    { 
     // get mad 
     printf("Enter 1 integer as an argument. Stop messing around!\n Try Again: "); 
     return 1; 
    } 
    else 
    { 
     //create command line arguments to be stored into k 
     k = atoi(argv[1]); 
     k = k * 1; 
    } 

    // Get text to be encrypted 
    printf("Enter the text you want to encrypt: \n"); 
    string a = GetString(); 

    string b = Crypto(a, k); 
    printf("%s\n", b); 

    return 0; 
} 

//Now let's get cryptic 
string 
Crypto(string a, int k) 
{ 
    int c = 0; 
    for (int i = 0, n = strlen(a); i < n; i++) 
    { 
     if(a[i] >= 65 && a[i] <= 90) 
     { 
      c = ((26 - (91 - a[i] + k) % 26)); 
      a[i] = c + 'A'; 
     } 
     else 
     { 
      c = ((26 - (123 - a[i] + k % 26))); 
      a[i] = c + 'a'; 
     } 
    } 
    return a; 
    } 
+0

Pranav讓我走在正確的道路上。我需要的是[strlen(a)+ i + 1] ='\ 0'; – cbanowsky 2014-12-07 06:43:30

+0

觀察:'argc'只有當它是2時纔是正確的,它最簡單準確地寫爲'if(argc!= 2)'(而不是'if(argc == 0 || argc == 1 || argc> 2)')。 – 2016-08-26 21:56:59

回答

1

在功能Crypto,則需要附加\0(空)字符以表示字符串的結尾。在return a;之前,寫一條a[i+1] = '\0';聲明。