怎样才能让intengers数组,其中每个数组的位置是我的号码的数字? [英] How can I make an array of intengers where each array position is a digit of my number?
问题描述
那么,我想这样做是在用户输入的二进制数(即1010010100111000001),并将其存储在一个数组,其中每个数组位置与我的号码的数字相关的小程序。
例如:位[0] = 1,位[1] = 0等,code我心目中是这样的,但我不相信它的工作原理:
So what I'm thinking about doing is a little program where the user inputs a binary number (i.e 1010010100111000001), and then it is stored in an array, where each array position is associated with a digit of my number. Example: bit[0] = 1, bit[1] = 0 etc. The code I have in mind is this but i don't believe it works:
int bit [31];
scanf("%i", bit);
请帮助!
推荐答案
的主要问题是如何保证用户输入有效的二进制数,即,专门的0和1。你可以尝试读取字符输入字符,并检查输入使用标准sscanf的格式正确的:%[01]
。还应该限制输入的大小,以一个单独的字符。因此,最终的格式为: 1%[01]
The main problem is how to ensure the user enters a valid binary number, i.e. exclusively 0s and 1s. You can try to read the inputs character by character and check the input is valid by using the standard sscanf format: %[01]
. You should also limit the size of the input to a single character. Hence the final format: %1[01]
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
int bits[31];
char input[2];
int i;
int j;
fprintf(stdout, "Enter at most 31 bits: ");
for(i=0; i<31 && 1 == fscanf(stdin, "%1[01]", input); ++i)
bits[i] = (input[0]=='1' ? 1 : 0);
fprintf(stdout, "You entered: \n");
for(j=0; j<i; ++j)
fputc(bits[j]?'1':'0', stdout);
fprintf(stdout, "\n");
return 0;
}
这篇关于怎样才能让intengers数组,其中每个数组的位置是我的号码的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!