gpt4 book ai didi

c - 如何输入未知大小的字符串

转载 作者:太空狗 更新时间:2023-10-29 17:09:12 26 4
gpt4 key购买 nike

我对 C 中的字符串有点困惑。我知道声明缓冲区大小很重要,否则会导致缓冲区溢出。但是我需要知道如何获取一个我不知道其大小的字符串输入。例如,如果我想从用户那里获取一行文本作为输入,但我无法知道他们的文本有多长,我该怎么做?

我试过在用户输入时动态分配内存。这是代码-

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

int main()
{
char *str, ch;
int size = 10, len = 0;
str = realloc(NULL, sizeof(char)*size);
if (!str)return str;
while (EOF != scanf_s("%c", &ch) && ch != '\n')
{
str[len++] = ch;
if (len == size)
{
str = realloc(str, sizeof(char)*(size += 10));
if (!str)return str;
}
}
str[len] = '\0';
printf("%s\n", str);
free(str);
}

问题是,当我使用 VS-2017 编译它时,出现了这些错误-

source.c(10): warning C4473: 'scanf_s' : not enough arguments passed for format string

source.c(10): note: placeholders and their parameters expect 2 variadic arguments, but 1 were provided

source.c(10): note: the missing variadic argument 2 is required by format string '%c'

source.c(10): note: this argument is used as a buffer size

我认为我继续动态分配内存(如上面的代码)应该可行,但我可能做错了什么。有什么办法可以做到这一点吗?

编辑:单词。

最佳答案

  1. 您应该使用 getchar 而不是 scanf_s
  2. 对于 EOF,您应该使用 int ch; 而不是 char ch;

以下代码可以工作:

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

int main() {
char *str = NULL;
int ch;
size_t size = 0, len = 0;

while ((ch=getchar()) != EOF && ch != '\n') {
if (len + 1 >= size)
{
size = size * 2 + 1;
str = realloc(str, sizeof(char)*size);
}
str[len++] = ch;
}
if (str != NULL) {
str[len] = '\0';
printf("%s\n", str);
free(str);
}

return 0;
}

关于c - 如何输入未知大小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com