简体   繁体   中英

How can I break a number that I input in the terminal into digits?

Ok so what I have to do is input a binary number IN THE TERMINAL, probably using argv[] or something, and then break it into each digit. What I have is this:

int bits[31];
for(int i=0; i<31 && 1 == fscanf(stdin, "%1d", &bits[i]); ++i);

This works for the scanf, but I would want a SIMPLE way of doing so but with the input being in the terminal

This code accepts a binary number as the program argument. Most of the code is devoted to weeding out any invalid argument.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int len;
    long bin;
    if (argc < 2) {
        printf("Please try again with an argument supplied\n");
        return 1;
    }
    len = strlen(argv[1]);
    if (strspn(argv[1], "01") != len) {
        printf("The argument is not a binary number\n");
        return 1;
    }
    printf("First bit is %c\n", argv[1][0]);
    printf("Last bit is %c\n", argv[1][len-1]);

    bin = strtol(argv[1], NULL, 2);
    printf("As a long integer variable, the input is %ld\n", bin);
    return 0;
} 

Without error checking (except against crashing), this reduces to

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int len;
    if (argc > 1) {
        len = strlen(argv[1]);
        printf("First bit is %c\n", argv[1][0]);
        printf("Last bit is %c\n", argv[1][len-1]);
        printf("As a long integer the input is %ld\n", strtol(argv[1], NULL, 2));
    }
    return 0;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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