C:将int数组作为输入而没有循环?

时间:2014-07-30 19:30:18

标签: c arrays

所以我有这段代码:

int main(){
 printf("How many members are they?");
 int howManyMember;
 scanf("%d",&howManyMember);
 int theListOfNumber[howManyMember];
 /* Asks for some user entered numbers */
 /* Then prints the array */
 return 0;
}

我想要先前用户输入""来自用户的号码数量,但是我被告知不要在循环中询问,所以不会出现这种情况。

int x;
for (x=0;x<howManyMember; x++){
 scanf("%d",&theListOfNumber[x])
}

所以当我得到输入时,我会得到输入

arrayMember0 arrayMember1 ... arrayMemberN

arrayMember0
arrayMember1
arrayMember...
arrayMemberN

我试过了fgets()但事实证明只有字符串。任何帮助将不胜感激=)

注意:请注意,要求的号码数量不固定。它基于用户输入。 谢谢!

4 个答案:

答案 0 :(得分:2)

您拥有的代码,

for (int x=0;x<howManyMember; x++){
 scanf("%d", &theListOfNumber[x])
}

非常好。

您可以使用它从一行或多行读取数据。

答案 1 :(得分:2)

您可以使用fgets来读取该行,然后使用strtok对其进行标记,并使用空格作为分隔符。

请参阅http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

答案 2 :(得分:1)

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

int count = 0;
int getss(int array[], int size)
{
    scanf("%d", &array[count]);
    count++;
    size>1 && getss(array, size - 1);
    return 0;
}
int main()
{
    int aji[20],n;
    printf("\nRecursion program enter size:");
    scanf("%d",&n);
    getss(aji,n);

return 0;
}

答案 3 :(得分:0)

int main (int argc, char *argv[])
{
    static void *test;
    static int howManyMember;
    if (argv) {
        printf("How many members are they?");
        scanf("%d", &howManyMember);
        if (howManyMember > 0) {
            int theListOfNumber[howManyMember];
            test = theListOfNumber;
            main(0, 0);
            int x;
            for (x = 0; x < howManyMember; ++x) {
                printf("got: %d\n", theListOfNumber[x]);
            }
        }
    } else if (argc < howManyMember) {
        int *theListOfNumber = test;
        scanf("%d", theListOfNumber + argc);
        main(argc+1, 0);
    }
    return 0;
}

Live demo.