C - Read a single int at the time

北城以北 提交于 2020-01-16 02:55:05

问题


I have this input:

Input: 2015

And I want to scanf him like this:

scanf("%1d", &arr);

But this is definitely wrong. What can I do? I want to receive the input integer by integer like '2','0','1','5' , and not like "2015".


回答1:


Just read each character individually, and convert the individual chars to integers.

#include <stdio.h>

int main(int argc, char* argv[])
{
    size_t len, i;
    char buff[64];

    fgets(buff, sizeof(buff), stdin);

    for(i = 0, len = strlen(buff); i < len; ++i) {
        int curr = buff[i] - '0'; /* subtracting '0' converts the char to an int */
        printf("%d\n", curr);
    }
}



回答2:


If your input is fixed size like 2015 then you can use

int arr[4];
for(int i=0; i<4; i++){
    scanf("%1d", arr+i);
}

But for general case you can read as string using fgets.




回答3:


I suggest to read the entire line, then parse it specifically.

To read a line on POSIX systems use getline(3), which will allocate the line buffer in heap (don't forget to initialize the pointer containing the line to NULL and the variable size to 0, and free the line where you are done). If you are unlucky to be on a system without getline, declare a large (e.g. 256 bytes at least) buffer and use fgets(3). BTW, on Linux, for editable input from the terminal -a.k.a. a tty- (not a pipe or a file, so test with isatty(3)) you could even consider using readline(3); try it once, it is very handy!

Once the entire line is in memory, you can parse it (provided you defined the syntax of that line, at least in your head; an example is often not enough; you might want to use EBNF in your documentation).

You could use sscanf(3) to parse that line or parse it manually with some iterative code, etc... Don't forget to check the returned count of scanned items. Perhaps %n can be handy (to get a byte count). You could also parse that line manually, or use strtol(3) for parsing long numbers, (or perhaps strtok(3) which I dislike because it is stateful) etc...



来源:https://stackoverflow.com/questions/33047736/c-read-a-single-int-at-the-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!