c - 我正在使用 while 循环来一一输入字符(要输入的字符总数未知)。如何将我的字符存储在数组 : 中

标签 c getchar putchar

用户必须输入未知长度的字符串(<1000)。所以这里我使用 while 循环、#definegetchar
我应该怎么做才能同时存储字符?

#include <stdio.h>
#define EOL '\n'

int main()
{
    int count=0;
    char c;

    while((c=getchar())!= EOL)// These c's have to be stored.
    {
        count++;
    }

    return 0;
}

编辑:抱歉我没有早点告诉你这件事。如果 count!=1000,我就不必浪费 1000 个字节。这就是为什么我最初没有声明任何包含 1000 个元素的数组。

最佳答案

实现动态增长的数组

  1. 使用 calloc()malloc() 分配一个小内存块 - 假设 10 个字符

  2. 如果需要,使用realloc()增加内存块的大小

示例:

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

#define EOL '\n'

int main()
{
    int count = 0;
    int size = 10;
    char *chars = NULL;
    char c;
    
    /* allocate memory for 10 chars */
    chars = calloc(size, sizeof(c));
    if(chars == NULL) {
        printf("allocating memory failed!\n");
        return EXIT_FAILURE;
    }

    /* read chars ... */
    while((c = getchar()) != EOL) {
        /* re-allocate memory for another 10 chars if needed */
        if (count >= size) {
            size += size;
            chars = realloc(chars, size * sizeof(c));
            if(chars == NULL) {
                printf("re-allocating memory failed!\n");
                return EXIT_FAILURE;
            }
        }
        chars[count++] = c;
    }

    printf("chars: %s\n", chars);

    return EXIT_SUCCESS;
}

关于c - 我正在使用 while 循环来一一输入字符(要输入的字符总数未知)。如何将我的字符存储在数组 : 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966754/

相关文章:

链表中的连续动态内存分配

c - Linux 中 kmemdup_nul() 和 kstrndup() 有什么区别?

c - 将 int 作为 char 添加到 char[ ]

c++ - 我怎样才能通过 getchar();不按回车,让它自动?

c - 在C编程中达到EOF时如何退出stdin

c - 为什么 putchar() 不输出版权符号而 printf() 输出版权符号?

c - C 编程语言,第 1 章练习 1.10(Getchar 和 Putchar)

c - STM32F4 ADC DMA 配置不工作

c - 当我输入文本流时,c=getchar 如何使用缓冲区输出文本流?

c - 使用 getchar() 存储数字