2012-11-16 71 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