c - 来自单个输入的多个 scanf

标签 c

我试图提示用户输入一个数字,然后提取他们输入的数字并对他们输入的数字进行求和。他们只能输入该号码一次。我的代码如下:

    printf("\nPART 2: EXPRESSIONS SUM\n\n");
    printf("Enter 5-digit integer: ");
    scanf("\n%1d%1d%1d%1d%1d", &dig_one, &dig_two, &dig_three, &dig_four, &dig_five);
    scanf("\n%d", &five_dig_int)

但是,在第一个 scanf 完成后,程序会卡在第二个 scanf 上,等待更多输入。有没有一种方法可以“重新扫描”初始输入,这样用户就不必再次输入号码?谢谢! ;

最佳答案

使用字符串和atoi()

示例:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    char str[6];
    printf("\nPART 2: EXPRESSIONS SUM\n\n");
    printf("Enter 5-digit integer: ");
    scanf("\n%s, &str);
    int fivedigit = atoi(str);
    int sum = 0;
    for(int i = 0; i < 5; i++)
    {
        int tempadd = (int) str[i];
        sum += tempadd;
    }
    //Do stuff with both values



}

关于c - 来自单个输入的多个 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186607/

相关文章:

c - 像 unsigned int 一样右移二进制补码

当函数指针被分配给另一个文件中具有相同名称的函数时,核心转储

c++ - "#define FOO(template)"是做什么的?

c - 数组和指针与函数的和

c - 检查何时没有任何内容通过管道传输到标准输入

c - gcc 无法在没有 -O2 的情况下内联函数

c - 从字符指针打印字符

c - 如何使用 malloc 将 C 中的 int 变量转换为 char *array?

c - 使用 SDCC (Little Endian) 编译器时这个算法有什么问题?

没有 Stackoverflow 的 C 卷积