ユーザー入力を受け取って画面に出力するプログラムを作成します。
サンプル入力は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;
}