如何将我在终端输入的数字分成数字?

时间:2015-04-03 14:30:06

标签: c arrays input terminal numbers

好的,我要做的是输入二进制数IN IN TERMINAL,可能使用argv []或其他东西,然后将其分成每个数字。 我有这个:

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

这适用于scanf,但我想要一种简单的方法,但输入在终端

1 个答案:

答案 0 :(得分:0)

此代码接受二进制数作为程序参数。大多数代码都致力于清除任何无效的参数。

#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;
} 

没有错误检查(崩溃除外),这会减少到

#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;
}