以用户的输入并将其存储在串C中的阵列(Taking user input and storing i

2019-10-23 04:52发布

我是新的C和尝试写一个命令行应用程序,做的基于用户输入的东西一大堆。 我需要在无限循环运行程序并读取用户输入的字符串数组。

我用while循环它被写入到一个字符串。

while(fgets(str, 256, stdin)){

}

现在我有点困惑如何修改这个循环写入字符串到直接用空格作为分隔符的数组。

所以,如果我有一个输入

Terminate client 2345

阵列应具有与所述第一感终止3个元素。 任何帮助表示赞赏。

Answer 1:

该过程基本上是一样的,不管你是否读取stdin或从文件中读取。 你要么阅读与面向线路输入 (每行fgetsgetline ),或者你使用面向字符的输入( getcharfgetc ,等等)。 (在scanf家族在中间下降)。 当读线 ,通常最好的选择是面向行的输入。

当读取用户输入到一个数组,你有两个选择,要么宣布一个静态的指针数组,并希望您分配了足够的指针开始,或者你动态分配的指针数组和realloc需要来保存所有输入。 (谁知道,用户可以重定向一个文件进行读取)。 当你动态地分配任何有责任跟踪其使用,保存一个指向原来的起始地址的内存块,并free ING不再需要它的时候的记忆。

以下是从服用输入标准例如stdin并将其存储在动态分配的数组。 有一个转折。 该代码可以从文件或处理输入stdin 。 如果给出文件名作为第一个参数,那么它会读取该文件,否则就从标准输入读取。 它期望用户根据需要提供尽可能多的输入,然后按[ctrl+d]完成时。 (手动生成EOF )。

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

#define NMAX 128

int main (int argc, char **argv) {

    char *ln = NULL;                /* NULL forces getline to allocate  */
    size_t n = 0;                   /* initial ln size, getline decides */
    ssize_t nchr = 0;               /* number of chars actually read    */
    size_t idx = 0;                 /* array index counter              */
    size_t nmax = NMAX;             /* check for reallocation           */
    char **array = NULL;            /* array to hold lines read         */
    FILE *fp = NULL;                /* file pointer to open file fn     */

    if (argc > 1) {
        if (!(fp = fopen (argv[1], "r"))) {
            fprintf (stderr, "error: file open failed for '%s'\n", argv[1]);
            return 1;
        }
    }
    else
        fp = stdin;

    /* allocate NMAX pointers to char* */
    if (!(array = calloc (NMAX, sizeof *array))) {
        fprintf (stderr, "error: memory allocation failed.");
        return 1;
    }

    if (fp == stdin)
        printf ("\nEnter information to store in array on each line, [ctrl+d] when done:\n\n");

    /* read each line from file or stdin - dynamicallly allocated   */
    while ((nchr = getline (&ln, &n, fp)) != -1)
    {
        /* strip newline or carriage rtn    */
        while (nchr > 0 && (ln[nchr-1] == '\n' || ln[nchr-1] == '\r'))
            ln[--nchr] = 0;

        array[idx] = strdup (ln);   /* allocate/copy ln to array        */

        idx++;                      /* increment value at index         */

        if (idx == nmax) {          /* if lines exceed nmax, reallocate */
            char **tmp = realloc (array, nmax * 2 * sizeof *tmp);
            if (!tmp) {
                fprintf (stderr, "error: memory exhausted.\n");
                break;
            }
            array = tmp;
            nmax *= 2;
        }
    }

    if (ln) free (ln);              /* free memory allocated by getline */
    if (fp != stdin) fclose (fp);   /* close open file descriptor       */

    size_t i = 0;

    /* print array */
    printf ("\nThe lines in the file are:\n\n");
    for (i = 0; i < idx; i++)
        printf (" line[%3zu] : %s\n", i, array[i]);

    /* free array */
    for (i = 0; i < idx; i++)
        free (array[i]);
    free (array);

    return 0;
}

实施例/输出

$ ./bin/getline_readstdin_dyn

Enter information to store in array on each line, [ctrl+d] when done:

This is a line of input
This is another
and another
etc..

The lines in the file are:

 line[  0] : This is a line of input
 line[  1] : This is another
 line[  2] : and another
 line[  3] : etc..

或从文件中读取:

$ ./bin/getline_readstdin_dyn dat/ll_replace_poem.txt

The lines in the file are:

 line[  0] : Eye have a spelling chequer,
 line[  1] : It came with my Pea Sea.
 line[  2] : It plane lee marks four my revue,
 line[  3] : Miss Steaks I can knot sea.
 line[  4] : Eye strike the quays and type a whirred,
 line[  5] : And weight four it two say,
 line[  6] : Weather eye am write oar wrong,
 line[  7] : It tells me straight aweigh.
 line[  8] : Eye ran this poem threw it,
 line[  9] : Your shore real glad two no.
 line[ 10] : Its vary polished in its weigh.
 line[ 11] : My chequer tolled me sew.
 line[ 12] : A chequer is a bless thing,
 line[ 13] : It freeze yew lodes of thyme.
 line[ 14] : It helps me right all stiles of righting,
 line[ 15] : And aides me when eye rime.
 line[ 16] : Each frays come posed up on my screen,
 line[ 17] : Eye trussed too bee a joule.
 line[ 18] : The chequer pours over every word,
 line[ 19] : Two cheque sum spelling rule.

输入重定向是罚款为好。 例如:

$ ./bin/getline_readstdin_dyn < dat/ll_replace_poem.txt


Answer 2:

在通知解析杂牌的风险,你有你的读取循环。 现在使用strtoksscanf通过令牌解析字符串转换成存储变量。 在这种设置中,我怀疑strdup是更好的选择。



文章来源: Taking user input and storing it in an array of strings in C
标签: c arrays