1

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

Pedro Cabaco
  • 165
  • 1
  • 11
  • why not use `char bits[31]`, read the input with `scanf("%s",bits)` and when you'd like to use a digit take `bits[index]-'0'` – yiabiten Apr 03 '15 at 14:36
  • Ok but this is working for scanf.. I just wanna do the input on the terminal and not with scanf... – Pedro Cabaco Apr 03 '15 at 14:44
  • 1
    `scanf()` reads from 'the terminal'. You mention `argv`; do you mean 'supply the number on the command line'? If so, then you need to read [How to use `sscanf()` in loops?](http://stackoverflow.com/questions/3975236/how-to-use-sscanf-in-loops). – Jonathan Leffler Apr 03 '15 at 14:54
  • yeah i didn't really get how i can make it input in the terminal.. what would you change in my solution? – Pedro Cabaco Apr 03 '15 at 15:10
  • use `argv[1]` and `sscanf` like as http://stackoverflow.com/a/29432747/971127 – BLUEPIXY Apr 03 '15 at 15:31

1 Answers1

0

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;
} 
Weather Vane
  • 33,872
  • 7
  • 36
  • 56