简体   繁体   English

C字符串atoi int数组

[英]C string atoi int array

I want to do the following stuff: 我想做以下事情:

  1. Convert input string to int. 将输入字符串转换为int。
  2. Sum up an int array by using pointers and a for loop. 通过使用指针和for循环来汇总int数组。
  3. If the user types nothing but only ENTER, the program will print the answer. 如果用户只输入ENTER,程序将打印答案。

My code: 我的代码:

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;
}

There is something weird that I can't figure out why. 有些奇怪我无法弄清楚为什么。

It only works fine with two-digits: 它只适用于两位数:

$Please enter some numbers:
$32
$31
$1
$
$sum:64

If I type three-digits, it directly prints result: 如果我输入三位数,它会直接打印结果:

$Please enter some numbers:
$123
$sum:123


$Please enter some numbers:
$12
$123
$sum:135

If there are more than three digits, the program will sum up rest of the digits. 如果超过三位数,程序将总结其余数字。

$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).

If someone can help me, I would be grateful. 如果有人可以帮助我,我将不胜感激。 Thank you for reading this long question. 感谢您阅读这个长期的问题。

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 *bint的大小(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM