-1

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

#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 个元素的数组。

4

2 回答 2

1

如果您不知道字符串中有多少个字符,但有一个硬​​性上限,您可以简单地为该上限分配足够的空间:

char tmpArray[1000];

将字符存储在其中:

while((c=getchar())!=EOL)
{
    tmpArray[count] = c;
    count++;
}

然后在你的循环完成并且你知道有多少个字符(通过计数变量)之后,你可以分配一个具有正确数量的新数组并将临时字符串复制到其中:

char actualArray[count];
for(int i = 0;i < count + 1;i++) {
    actualArray[i] = tmpArray[i];
}

但是,这并不是很好,因为无法从内存中释放/删除大型数组。使用 malloc 和 char* 来执行此操作可能是一个更好的主意:

char* tmpArray = malloc((sizeof(char)) * 1001);
while((c=getchar())!=EOL) {
    tmpArray[count] = c;
    count++;
}

char* actualArray = malloc((sizeof(char)) * count + 1);
strncpy(actualArray, tmpArray, count + 1);
free(tmpArray);

/***later in the program, once you are done with array***/
free(actualArray);

strncpy 的参数是 (destination, source, num),其中 num 是要传输的字符数。我们将计数加一,以便字符串末尾的空终止符也被传输。

于 2015-08-12T13:51:39.863 回答
1

实现一个动态增长的数组

  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;
}
于 2015-08-12T14:12:51.687 回答