首页 > 解决方案 > 当用户在 C 中输入“#”时,停止将字符串连接到动态数组

问题描述

我需要编写一个代码,我不断地从用户那里读取一个字符串输入并将其存储在同一个变量中。每次收到输入时,字符串都会连接到动态数组中(因此动态数组会越来越大)。当输入包含“#”时,它将停止读取用户的输入。

预期的输入和输出应该是:

inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

这是我完成的代码:

#include<stdio.h>
#include<stdlib.h> // for malloc
#include<string.h> // for string funs

int main(void){
    char input1[256];
    char *combined = malloc(sizeof(char));
    int i = 0;

    while (input1[i]!= '#'){  
    // read in the arrays
    printf("Enter a string (max 256 char) ");
    scanf("%256s",input1);

    // find out string lengths
    int len1;
    len1=strlen(input1);

     // allocate an array big enough for both
     combined=realloc(combined, sizeof(char)*(len1));

     //concatenate
     strcat(combined,input1);
    }


    // print
    printf("%s\n",combined);

    return 0;
}

我这里的这段代码有几个问题:

  1. 我不知道如何检查用户输入的第一个元素以外的元素是否为“#”。
  2. 即使输入包含“#”,输出仍将包含“#”所在的输入。

谁能给我提示如何解决这个问题?谢谢!

标签: cdynamic-arrays

解决方案


你可能会让你自己变得更难,这需要。虽然您的标题为 2 列输出会增加一些格式挑战,但处理输入和分类(存储/忽略它)的最简单方法是使用面向字符的方法getchar()or fgetc()

这样,您只需不断地从输入中读取并检查字符是否为 a'#''\n',如果是,则停止将字符存储在缓冲区中并仅读取并输出其余字符。循环完成后,您只需要终止最终缓冲区,计算原始缓冲区和缓冲区内容输出之间所需的空白,写入空格和最终缓冲区即可。一个简短的例子是:

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

#define MAXC 1024   /* if you need a constant, #define one (or more) */

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

    char buf[MAXC];
    int c, idx = 0, nc = 0, ws = 0;
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    puts ("inputs              output");    /* output headings */
    while ((c = fgetc(fp)) != EOF) {        /* read each char until EOF */
        if (c == '#' || c == '\n') {        /* if # or \n, end of storage */
            buf[idx] = 0;                   /* nul-terminate buffer at idx */
            putchar (c);                    /* output delim in orig string */
            nc++;                           /* increment no. of char  */
            while ((c = fgetc(fp)) != '\n' && c != EOF) {   /* print rest */
                putchar (c);
                nc++;
            }
            ws = 20 - nc;           /* compute amount of whitespace to col */
            while (ws--)            /* output that many spaces */
                putchar (' ');
            printf ("%s\n", buf);   /* print the stored buffer */
            idx = 0, nc = 0;        /* reset index and counter */
            continue;               /* go get next char */
        }
        else if (isalnum (c))       /* if alnum char add to buffer */
            buf[idx++] = c;
        putchar (c);        /* output all chars until # */
        nc++;               /* increment no. of chars */
    }
    buf[idx] = 0;           /* nul-terminate final line after loop */
    ws = 20 - nc;           /* set number of whitespace needed to 2nd col */
    while (ws--)            /* write that number of spaces */
        putchar (' ');
    printf ("%s\n", buf);   /* output string without whitespace in buf */

    if (fp != stdin)        /* close file if not reading stdin */
        fclose (fp);

    return 0;
}

示例输入文件

$ cat dat/pounddelim.txt
here I am #abc
there you are #12

示例使用/输出

在您的输入上运行程序会产生“预期的输入和输出”

$ ./bin/pounddelim <dat/pounddelim.txt
inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

如果您还有其他问题,请仔细查看并告诉我。


推荐阅读