c - 如何从一行中读取多个整数?

标签 c input

输入是一行中由空格分隔的一些整数,如下所示:

   enter numbers: 12 41 2

程序应该获取每个整数并显示总和:

   sum: 55

我该怎么做?

编辑:我试过了,但无法检测到回车键。当按下 enter 时,它应该停止并显示总和。

printf("\nEnter numbers: ");
int sum =0;
int temp;
while( scanf("%d",&temp))
{
    sum+=temp;

}
printf("Sum: %d",sum);

最佳答案

#include <stdio.h>

int main(){
    printf("\nEnter numbers: ");
    int sum =0, temp;
    char ch;
    while(2 == scanf("%d%c", &temp, &ch)){
        sum+=temp;
        if(ch == '\n')
            break;
        else if(ch != ' '){
            fprintf(stderr, "Invalid input.\n");
            return -1;
        }
    }
    printf("Sum: %d\n", sum);
    return 0;
}

关于c - 如何从一行中读取多个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23023458/

相关文章:

javascript - native 日期输入忽略 CSS

c - 如果我打算将文件拆分为字符串,如何读取文件中的每一行? C

c++ - 使用 WM_CHAR 消息发出键盘输入?

c - 如何在钩子(Hook)程序中将复选框绘制到消息框上?

c++ - 如何以编程方式查找为 Linux 中的特定网络设备配置的 IP 地址/网络掩码/网关?

c - typedef 结构作为指针?

c - 将无符号字符数组作为参数传递 - 数组未正确传递

javascript - 如何使用文本框中的输入来更改 iframe url 的一部分?

python - 如何正确运行 2 个同时等待事物的线程?

r - 错误: path for html_dependency not provided R Markdown selectInput