2016-02-19 121 views
-3

你好,我是相當新的編程在C和基本上解密數組只有持有的第一個值輸入到下面是我的代碼還有任何提示,以幫助我提高,我們感激;C與數組的麻煩,

int main(int argc, char *argv[]) { 
char input[100] = ""; 
char target[100] = ""; 
char replace[100] = ""; 
char keycipher[100] = ""; 
int i, size; 
static char decrypt[100] = ""; 

while(1){ 
    printf("\nEnter Target: "); 
    fgets(target, 17, stdin); 

    printf("Replace With: "); 
    fgets(replace, 17, stdin); 

    for(i = 0; i < size; i++) 
    { 
     if(input[i] == target[0]) { 
      decrypt[i] = target[i];<-this is where it is supposed to be added 
      input[i] = replace[0]; 
      printf("\n%s",input); 
      printf("\n%s",decrypt); 
     } 
    } 

    if(target[0] == 'q' || replace[0] == 'q'){ 
      break; 
    } 
} 

printf("decryt @# %s", decrypt); 
printf("\nDecrypting .....\n"); 
printf("Your orginal string was: "); 

for(i = 0; i < 100; i++) 
    { 
     input[i] = decrypt[i]; 
     printf("%s", input); 
    } 

printf("\nSIMULATION OVER!\n"); 

system("PAUSE"); 
return 0; 
} 

我收到的輸出如下;

*--------------------------* 
| Welcome to the Scrambler |  
*--------------------------* 
    Remember press q to quit 

Please enter a string: hello stranger 
you entered: hello stranger 

Enter target: h 
Replace with: w 

wello stranger 
decrypt array: h 

Enter target: s 
Replace with: p 

wello ptranger 
decrypt array: h <-------- why is this still just h? 

Enter target: q 
Replace with: 

decrypt holds: h <---------- 
Decrypting ..... 
Your original string was: hello ptrangerhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 

SIMULATION OVER! 

另外我該如何檢查目標是否已經在數組中,以便它們不能添加該字符?

+0

decrpyt是什麼意思?更精確。 –

+0

'請輸入一個字符串:你好,陌生人 你輸入了:hello stranger' ...怎麼回事? –

+0

用戶輸入他們交換字符串的字符,我試圖將他們的輸入保存到數組中,以在完成後用作解密密鑰。 – Ryan

回答

1

的問題是在

char target[0] = ""; 
char replace[0] = ""; 

零長度數組不能用於有意義unless it is the last member of a struct柔性陣列構件)。

您需要分配爲適用於您的上下文有意義的長度,像

#define LINSIZ 128 

char target[LINSIZ ] = ""; 
char replace[LINSIZ ] = ""; 

這就是說,你永遠不會初始化size,AO,後來

for(i = 0; i < size; i++) 

基本上嘗試讀取未初始化的自動局部變量的值,它具有不確定的值。它調用調用undefined behavior

+0

我已經初始化了變量,我只是刪除它來嘗試減少你讀的代碼量,它的這個大小=(sizeof input/sizeof input [0]); – Ryan

0

由於您使用的是0長度數組並使用超出邊界索引訪問它們,因此您的程序受未定義的行爲影響。

char target[0] = ""; 
char replace[0] = ""; 

看着你的代碼,你可能需要它們大到input

char target[100] = ""; 
char replace[100] = "";