[英]C string atoi int array
int main(void)
{
int i, a[10], sum = 0;
int * b;
b = a;
char c[10];
printf ("Please enter some numbers:\n");
for(i = 0 ; i < 10 ; i++)
{
(void) fgets(c, (sizeof * b), stdin);
if(c[0] == '\n')
{
break;
}
*(b + i) = atoi(c);
sum = sum + *(b + i);
}
printf ("sum : %d \n", sum);
return 0;
}
$Please enter some numbers:
$32
$31
$1
$
$sum:64
$Please enter some numbers:
$123
$sum:123
$Please enter some numbers:
$12
$123
$sum:135
$Please enter some numbers:
$2123
$
$sum:215 //The sum became 212+3.
$Please enter some numbers:
$12345
$11
$
$sum:179 //The sum became 123+45+11.
$Please enter some numbers:
$123456
$sum:579 //If the number of digits is a multiple of 3, this program directly prints sum(=123+456).
This is wrong: 这是错的:
fgets(c,sizeof* b,stdin);
sizeof *b
is the size of an int
(tipically 4) and you want room for 10
characters: sizeof *b
是int
的大小(tip 4),你想要10
字符的空间:
fgets(c,sizeof c,stdin);
And notice that you don't need to strip the trailing new-line after fgets
in this concrete case, from the atoi
man: 请注意,在这个具体情况下,你不需要在
fgets
之后删除尾随的新行,来自atoi
man:
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
字符串可以包含在形成整数之后的其他字符,这些字符将被忽略并且对此函数的行为没有影响。
fgets(c,sizeof(c),stdin);
size_t n = strlen(c);
if(n>0 && c[n-1] == '\n')
{
c[n-1] = '\0';
}
There is a newline character that comes with fgets()
you need to get rid of it. fgets()
附带一个换行符,你需要摆脱它。
Then convert the string to integer you don't know how many integers are there. 然后将字符串转换为整数,你不知道有多少整数。
char *p;
p = strtok(c," ");
while(p != NULL)
{
b[i++] = atoi(p);
p = strtok(c, NULL);
}
Do the addition of the integers and make sure you have a check for i<10
before accessing the array. 添加整数并确保在访问阵列之前检查
i<10
。
If your termination condition is \\n
before stripping the newline you can do the check what you are already doing. 如果在剥离换行符之前你的终止条件是
\\n
,你可以检查你已经在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.