我编写了一个程序来接收用户输入并将其打印到屏幕上。
样本输入为abc 12 34
。
样本输出为abc 12 34
,但12
和34
应作为整数输入。
使用示例输入,我的程序始终输出为abc 122 344
. 我已经研究了很长时间,但我仍然无法弄清楚。可以帮我检查我的代码吗?谢谢。
我的 gcc 版本是 4.1.2 。
#include<stdio.h>
#include<stdlib.h>
int main()
{
char c;
char *str = NULL;
str = (char *)malloc(20*sizeof(char)); /*just sample code, not robust*/
memset(str,'\0',20*sizeof(char));
if(str == NULL)
{
fprintf(stderr,"Error: failed to allocate memory.\n"); fflush(stderr);
return 0;
}
/*store user input*/
int index = 0;
while((c=getchar()) != '\n')
{
*(str+index) = c;
index++;
}
int digit = 0;
for(index = 0; *(str+index)>0; index++)
{
if((*(str+index)>='a') &&( *(str+index)<='z'))
{
fprintf(stdout,"%c",*(str+index)); fflush(stdout);
}
else if((*(str+index)>='0') &&( *(str+index)<='9'))
{
/*handling the case that a number with more than one digit*/
if(*(str+index+1)>='0' && *(str+index+1)<='9')
{
digit=10*(digit+atoi(str+index));
}
else
{
digit += atoi(str+index);
fprintf(stdout,"%d",digit); fflush(stdout);
digit = 0;
}
}
else
{
fprintf(stdout,"%c",*(str+index)); fflush(stdout);
}
}
printf("\n");
free(str);
return 0;
}