c - 如何将我在终端中输入的数字分解为数字?

标签 c arrays input terminal numbers

好的,所以我要做的是在终端中输入一个二进制数,可能使用 argv[] 或其他东西,然后将其分解为每个数字。 我所拥有的是:

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

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

最佳答案

此代码接受一个二进制数作为程序参数。大部分代码专门用于清除任何无效参数。

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

关于c - 如何将我在终端中输入的数字分解为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29434115/

相关文章:

c++ - pthread_join中的 "status"到底代表什么以及如何查询

c - 如何在符号表中添加共享库版本信息

JAVA初学者: IF statement not working as intended - body of code not being called when it should?

javascript - 如果输入字段为空显示 div

java - 设计用户命令和多个输入

javascript - 带有范围 slider 的自定义表单中断,我不知道为什么

c - 将指针分配给另一个指针的地址

c - 重新定义;之前的定义是 'data variable'

java - 每次调用方法时如何增加数组[a][b]的大小?

arrays - 找到最长的子数组