2012-11-16 73 views
0

這個程序應該通過從他們的ascii值中減去97(輸入應該是小寫,因爲ascii的值爲97)來將字符串(字符串)數組轉換爲一個整數的數組。所以,如果我輸入字符串abcd我應該得到0123,但我不知何故得到這個:012134513789.我不知道問題在哪裏。這會將char數組轉換爲int數組無效嗎?

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 

void userEnter(int*pattern, int n); 



int main(void) 
{ 
int n, i; 
printf("What is the length of the array: "); 
scanf("%d",&n); 
int pattern[n]; 
printf("Enter the char array: "); 
userEnter(pattern, n); 
printf("The int array is: "); 
for(i=0;i<n;i++) 
{ 
printf("%d",pattern[i]); 
} 
printf("\n"); 

} 

void userEnter(int*pattern, int n) 
{ 
    char input[n]; 
    scanf("%s", input); 

    int i; 
    for(i = 0; i < n-1; i++) 
    { 
     pattern[i] = input[i]-97; 
    } 
} 
+0

請使用有效的語法並正確縮進您的代碼。 –

+1

'scanf(「%s」,輸入)''有一個等待緩衝區溢出;',如果輸入超過n-1個字符,可以通過在'main'中覆蓋'n'來產生這樣的輸出。如果你永遠不會輸入超過n-1個字符,它應該工作,並在這裏做。 –

回答

1
char input[n]; 
scanf("%s", &input); 

應該

char input[n+1]; 
scanf("%s", input); 

input相當於&input[0]

你也應該退出for循環userEnter當您遇到結束用戶輸入的字符串空字符。例如喜歡的東西

char* p = input; 
while (*p != '\0') { 
    *pattern = (*p) - 'a'; 
    p++; 
    pattern++; 
} 

由於KingsIndian所指出的,你還需要增加你的input緩衝區的大小。目前,你溢出該緩衝區並覆蓋循環計數器i;

+0

是的,我看到了,但即使如此,輸出也是一樣的。 – Easytoread

+0

我已經更新了我的答案,以解釋一些令人驚訝的輸出 – simonc

+0

感謝它現在的作品! – Easytoread

1

長度參數n也包含一個空字符。所以,如果您輸入的長度爲n 4,那麼您只能輸入3個字符,例如abc,因爲第四個爲空。

所以,你應該相應地更改聲明:

變化:

char input[n]; 

到:

char input[n+1]; 

請注意,只有因爲C99變長數組是允許的。

+0

非常感謝,它現在正在工作! – Easytoread