简体   繁体   English

c scanf整数与连续输入,但只需要读取一个

[英]c scanf integer with consective input but only need to read one

I got input like 12345679890 but I just want to read 1 integer at a time, that is read 1 then 2 then 3 ... and do some operations next. 我输入像12345679890,但我只想一次读取1个整数,即读取1然后2然后3 ...然后执行一些操作。 However when I use scanf, it read all the numbers ie 1234567890. Can anyone help? 但是,当我使用scanf时,它会读取所有数字,即1234567890.任何人都可以帮忙吗? Thank you!! 谢谢!!

This is the code that I have 这是我的代码

#include <stdio.h>

int main() {
    int input;
    scanf("%x",&input);

   while (scanf("%x",&input)==1){}
}

12345679890 is an integer, what you want to do is read one digit at a time. 12345679890 一个整数,您想要做的是一次读取一个数字 To do this, you would use the format string %1u rather than %x . 为此,您将使用格式字符串%1u而不是%x

For a start, %x specifies a hexadecimal item, meaning it will accept a through f as well, and %d would allow for a leading sign which you probably don't want. 首先, %x指定一个十六进制项,这意味着它也将接受af ,而%d将允许你可能不想要的前导符号。

In addition, you appear to consume (and throw away) the first digit before you enter the loop, so you would be better off with something like: 此外, 进入循环之前 ,您似乎消耗(并丢弃)第一个数字,因此您最好使用以下内容:

#include <stdio.h>

int main(void) {
    unsigned int digit;
    while (scanf("%1d", &digit) == 1) {
        //doSomethingWith(digit);
    }
    return 0;
}

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

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