c - 当用户在 C 中输入 '#' 时停止将字符串连接到动态数组

标签 c dynamic-arrays

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

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

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. I have no idea how to check if elements other than the first element of the user's input is '#' or not.
  2. Even if the input contains '#', the output will still contain that input where '#' is in it.

任何人都可以给我提示如何解决这个问题吗?谢谢!

最佳答案

你可能会让自己变得更难。虽然您的标题是 2 列输出增加了一些格式化挑战,但处理输入和分类(store-it/ignore-it)的最简单方法是使用面向字符的方法使用 getchar()fgetc()

这样你就可以不断地从输入中读取并检查字符是否是 '#''\n',如果是,停止在你的缓冲并读取并输出其余部分。循环完成后,您只需nul-terminate您的最终缓冲区,计算原始结尾和缓冲区内容输出之间所需的空白,写入空格和最终缓冲区,然后您完成。一个简短的例子是:

#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

检查一下,如果您还有其他问题,请告诉我。

关于c - 当用户在 C 中输入 '#' 时停止将字符串连接到动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56321628/

相关文章:

c - 左对齐和右对齐

c - 初始化结构数组时出错(类型不兼容)

c - 标准和决策问题

c++ - 动态数组输出问题

c++ - 重载运算符返回的对象在 C++ 中丢失数据

c - C中的快速随机数生成函数

c# - 通过 IIS 而不是通过控制台应用程序调用时,未镜像的代码会泄漏内存

c - 如何malloc 8*10^9 int 内存?

c++ - 如何在不使用STL的情况下在C++中编写动态异构集合?

c - 如何在C中实现动态数组?