如何在 scanf in 循环中添加数字?

How to add the numbers inside the scanf in loop?

有什么方法可以在 scanf 循环中添加所有数字?如果输入数字为负数,循环将停止。问题是负数也必须包含在总和中。

在这里,我设法得到了循环中重复的所有 positive scanf 值的总和,但是 negative 数字仍然没有包含在所有数字的总和中。

#include <stdio.h>

main()
{
    int z, x;

    printf("Enter a number:\n");
    z = 0;
    scanf("%d", &x);
    do
    {
        z += x;
        scanf(" %d", &x);
    } while (x >= 0);
    printf("Sum = %d ", z);

    return 0;
}

反转循环内的线应该这样做:

int z, x;
int ch;

printf("Enter a number:\n");
z = 0;
do
{
    if (scanf("%d", &x) == 1) // checking if parsing was successful
    {
        z += x; // if so, perform the sum
    }
    else
    {
        puts("Bad input");                             // if user inputs a bad value
        while((ch = getchar()) != '\n' && ch != EOF){} // you clear the input buffer
    }

} while (x >= 0);
printf("Sum = %d ", z);

请注意,我还删除了循环内的第一个 scanf,它不再需要了。

do ... while 循环中的语句顺序进行简单的重新排列(并删除前面的 scanf 调用)即可解决问题:

#include<stdio.h>

int main() // You are returning "0" so declare "int" as return type
{
    int x = 0, z = 0;   // Easier to initialize at the same time as declaration.
    printf("Enter a number:\n");
//  scanf ("%d", &x);   // Don't read here - do that inside the loop.
    do {
        int test = scanf(" %d", &x);  // Read as the FIRST statement in the loop ...
        if (test != 1) { // If the "scanf" call failed, we need to clear the input stream ...
            int c;
            while ((c = getchar()) != '\n' && c != EOF)
                ; // Clear any offending input
            if (c == EOF) break; // Probably can't recover from an EOF, so exit the while loop
        }
        else z += x;                  // ... then we can add X even if it's negative
    } while (x >= 0);                 // But end the loop when it IS negative anyway

    printf("Sum = %d ", z);
    return 0;
}

请注意,我添加了一个 test 变量以确保 scanf 操作成功。如果用户输入 foo(如 William Pursell 在评论中提到的),则输入缓冲区被清除,添加被跳过,并且将再次尝试读取。

我不确定你是否想将不包含负值的输入流作为错误处理,但你可以简单地这样做:

#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    int sum = 0, x, rv;
    while( 1 == (rv = scanf ("%d", &x)) ){
        sum += x;
        if( x < 0 ){
            break;
        }
    }
    if( rv == 0 ){
        fprintf(stderr, "Invalid input\n");
    } else {
        printf("Sum = %d\n", sum);
    }
    return rv == 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}

我认为以下行为是合理的:

$ echo 4 5 8 5| ./a.out
Sum = 22
$ echo 4 5 -1 5| ./a.out
Sum = 8
$ echo 4 5 not-an-integer 5| ./a.out
Invalid input