這個程序應該通過從他們的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;
}
}
請使用有效的語法並正確縮進您的代碼。 –
'scanf(「%s」,輸入)''有一個等待緩衝區溢出;',如果輸入超過n-1個字符,可以通過在'main'中覆蓋'n'來產生這樣的輸出。如果你永遠不會輸入超過n-1個字符,它應該工作,並在這裏做。 –