gpt4 book ai didi

c - 如何在 C 中使用用户输入制作字符串函数?

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:22 25 4
gpt4 key购买 nike

我知道如何使用内部用户输入的 int、double、float 来创建函数(我目前正在使用 scanf)。

int getData(){
int a;
scanf("%i",&a);
return a;
}

但是如何创建字符串类型和用户输入的函数,然后我们返回字符串类型的值呢?

最佳答案

C 字符串是以 NUL(零)字节结尾的 char 数组。数组通常作为指向第一个元素的指针传递。从函数返回的问题是指向的地址必须在函数的生命周期之后保持有效,这意味着它需要是 static 缓冲区(然后被任何后续调用覆盖到同一个函数,破坏早期的返回值)或由函数分配,在这种情况下,调用者负责释放它。

您提到的 scanf 对于读取交互式用户输入也有问题,例如,它可能会使输入处于意外状态,例如当您不使用行尾的换行符时nextscanf 的调用(可能在不相关的函数中)在遇到换行符时可能无法给出预期的结果。

将输入逐行读取到缓冲区通常更简单,例如使用 fgets,然后从那里解析行。 (一些输入您可以通过逐个字符地读取而无需缓冲区就可以解析,但此类代码通常会变得很长且难以快速跟进。)

读取任何可能包含换行符以外的空格的字符串的示例如下:

/// Read a line from stdin and return a `malloc`ed copy of it without
/// the trailing newline. The caller is responsible for `free`ing it.
char *readNewString(void) {
char buffer[1024];
if (!fgets(buffer, sizeof buffer, stdin)) {
return NULL; // read failed, e.g., EOF
}
int len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
buffer[--len] = '\0'; // remove the newline
// You may also wish to remove trailing and/or leading whitespace
} else {
// Invalid input
//
// Depending on the context you may wish to e.g.,
// consume input until newline/EOF or abort.
}
char *str = malloc(len + 1);
if (!str) {
return NULL; // out of memory (unlikely)
}
return strcpy(str, buffer); // or use `memcpy` but then be careful with length
}

另一种选择是让调用者提供缓冲区及其大小,然后在成功时返回相同的缓冲区,在失败时返回 NULL。这种方法具有优点是调用者可以决定何时重用缓冲区以及是否需要复制字符串或只读取一次并忘记。

关于c - 如何在 C 中使用用户输入制作字符串函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52441799/

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