C-读取一串数字

时间:2018-11-16 21:13:48

标签: c string numbers int

我想读取一串我不知道的数字(仅Intiger),而且我也不知道我将要读取多少个数字。每个都将由空格分隔。那么什么是最好的方法呢?

您不必编写代码或其他内容,我只想知道应该使用什么。

谢谢

3 个答案:

答案 0 :(得分:1)

您可以逐个字符地阅读。每次找到数字(字符从48到57)时,请添加到临时字符串中。当您有空格时,请尝试解析创建的字符串。然后将其清空。并将其继续到大字符串的结尾。

答案 1 :(得分:0)

我认为这可能有效

int main(){

    char name[100];
    printf("Insert numbers: ");
    fgets(name, 100, stdin);
    printf("Your numbers: %s\n", name);
    return 0;
}

答案 2 :(得分:0)

您必须循环阅读,跳过空格(请参阅isspace(3)),而在内部循环应阅读while (isdigit(getchar()))(请参阅isdigit(3)

我将编写一些代码(如果您不想被宠坏,请在对解决方案感到满意之前,不要阅读以下内容):

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

/* this macro calculates the number of elements of an array.
 * you must be carefull to always pass an array (not a pointer)
 * to effectively get the number of elements */
#define SIZE(arr) ((sizeof arr) / (sizeof arr[0]))

int main()
{
    int n = 0;
    int a[100];
    /* this has to be an int (not a char) see getchar() manpage */
    int last_char = 0;

    /* while n < number of elements of array a */
    while (n < SIZE(a)) {

        /* read the character into last_char and check if it is
         * a space, tab or newline */
        while (isspace(last_char = getchar()))
            continue;
        /* last_char is not a space, it can be EOF, a minus sign,
         * a digit, or something else (not a number) */

        if (last_char == EOF)
            break; /* exit the outer loop as we got no more input data */

        int neg = (last_char == '-'); /* check for negative number */
        if (neg) last_char = getchar(); /* advance */

        /* check for digits */
        if (isdigit(last_char)) {
            /* digits are consecutive chars starting at '0'.  We are 
             * assuming ASCII/ISO-LATIN-1/UTF-8 charset. This doesn't
             * work with IBM charsets. */
            int last_int = last_char - '0';
            while (isdigit(last_char = getchar())) {
                last_int *= 10;  /* multiply by the numeration base */
                last_int += last_char - '0'; /* see above */
            }
            /* we have a complete number, store it. */
            if (n >= SIZE(a)) { /* no more space to store numbers */
                fprintf(stderr,
                    "No space left on array a. MAX size is %d\n",
                    SIZE(a));
                exit(EXIT_FAILURE);
            }
            if (neg) last_int = -last_int;
            a[n++] = last_int;
        }

        /* next step is necessary, because we can be on a terminal and
         * be able to continue reading after an EOF is detected.  Above
         * check is done after a new read to the input device. */
        if (last_char == EOF)
            break;
    } /* while (n < SIZE(a) */

    printf("Number list (%d elements):", n);
    int i;
    for (i = 0; i < n; i++) {
        printf(" %d", a[i]);
    }
    printf("\n");
    exit(EXIT_SUCCESS);
} /* main */