以用户的输入并将其存储在字符串中的C中的数组 [英] Taking user input and storing it in an array of strings in C

查看:110
本文介绍了以用户的输入并将其存储在字符串中的C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to C and trying to write a command line application that does a whole host of things based on the user input. I need to run the program on an infinite loop and read user input into a string array.

我用whil​​e循环它被写入到一个字符串。

I've used the while loop to write it into a string.

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

}

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

Now I'm a little confused about how to modify this loop to write strings into an array directly using space as a delimiter.

所以,如果我有一个输入

So if I've an input

Terminate client 2345

数组应具有与该第一感终止3个元素。任何帮助AP preciated。

The array should have 3 elements with the first being Terminate. Any help appreciated.

推荐答案

这个过程基本上是一样的,不管你是否从标准输入读或从文件中读取。你要么阅读每一行的面向行输入(与fgets 函数getline ),或者你使用面向字符输入(的getchar 龟etc 等)。 (在 scanf函数家庭落在中间)。当读,一般最好选择面向行输入。

The process is basically the same regardless of whether you read from stdin or read from a file. You either read each line with line-oriented input (fgets or getline) or you use character-oriented input (getchar, fgetc, etc). (the scanf family falls in the middle). When reading lines, generally the best choice is line-oriented input.

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

When reading user input into an array, you have two choices, either declare a static array of pointers and hope you allocated enough pointers to begin with, or you dynamically allocate the array of pointers and realloc as needed to hold all input. (who knows, the user might redirect a file for reading). When you allocate anything dynamically you are responsible to track its use, preserve a pointer to the original starting address for the block of memory, and freeing the memory when it is no longer needed.

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

The following is a standard example of taking input from stdin and storing it in a dynamically allocated array. There is a twist. The code can handle input from a file or stdin. If a filename is given as the first argument, then it will read the file, otherwise it reads from stdin. It expects the user to provide as much input as required, and then press [ctrl+d] when done. (manually generating 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.

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

Redirecting input is fine as well. E.g.:

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

这篇关于以用户的输入并将其存储在字符串中的C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆