问:输入11 22 333 444 字符串,计算出4个数相加的结果
答:
#include <stdio.h>
#include <string.h>
int main()
{
char s[100] = {0};
int ret=0;
// gets(s);
scanf("%[^\n]]",s);
char *p = strtok(s," ");
while(p)
{
printf("%s\n",p);
ret += atoi(p);
p = strtok(NULL," ");
}
printf("result:%d\n",ret);
return 0;
}
更简单的版本:
#include <stdio.h>
int main()
{
int result = 0 , i;
char ch;
while(scanf("%d",&i)==1)
{
result += i;
while((ch = getchar())==' ');
if(ch == '\n')
break;
ungetc(ch,stdin); //将获取的数字退回去
}
printf("result:%d\n",result);
return 0;
}