简体   繁体   English

在scanf()中单独输入?

[英]Separate input in scanf()?

I want to separate a 5 digit number taken in through scanf() into three different variables. 我想将通过scanf()接收的5位数字分成三个不同的变量。 The first variable should have the first digit, the second should have the second 2 digits, and the third should have the last 2 digits. 第一个变量应具有第一位数字,第二个变量应具有后两位数字,而第三个变量应具有后两位数字。

I was thinking of something like this: 我在想这样的事情:

int num1;
int num2;
int num3;
scanf(%1d%2d%2d, &num1, &num2, &num3);

However, this doesn't work: it assigns the last two digits to every variable. 但是,这不起作用:它将最后两位数字分配给每个变量。

Is there any way to do this without separating the number after scanning in all 5 digits? 有没有办法在扫描完所有5位数字后不分隔数字呢?

Change this: 更改此:

scanf(%1d%2d%2d, &num1, &num2, &num3);

to this: 对此:

scanf("%1d%2d%2d", &num1, &num2, &num3);

since you forgot to use the double quotes. 因为您忘记了使用双引号。

See this example: 请参阅以下示例:

#include <stdio.h>

int main(void) {
    int num1, num2, num3;
    scanf("%1d%2d%2d", &num1, &num2, &num3);
    printf("%d %d %d\n", num1 ,num2, num3);
    return 0;
}

Output: 输出:

> 12345
1 23 45

See it for yourself in this Live Demo 在此现场演示中亲自观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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