c - 从用户输入中读取句子的功能

标签 c

我正在尝试使用我的函数从用户输入问题中读取句子,当我尝试调用它时它会跳过第二次尝试。有什么解决办法吗?

void readString(char *array, char * prompt, int size) {
    printf("%s", prompt);
    char c; int count=0;
    char * send = array;
    while ((c = getchar()) != '\n') {
        send[count] = c; count++;
        if (size < count){ free(array); break; } //lets u reserve the last index for '\0'
        }

    }

下面是尝试如何调用它:

char obligation[1500];
char dodatno[1500];

readString(obligation, "Enter obligation", 1500);
readString(dodatno, "Enter hours", 1500);

这是输入示例: "这是一些句子"

所以后来我想这样做:

printf(" %s | %s \n",obligation, dodatno);

并得到:

This is some sentence|This is another sentence

最佳答案

在您的readString() 函数中,

  1. array 不是由 malloc() 或 family 动态分配的内存。

    使用未分配内存的指针调用 free() 会动态创建未定义的行为。

  2. getchar() 返回一个 int。您应该将 c 的类型更改为 int c

  3. 此外,readString() 中的输入没有空值终止,因此您不能直接将数组用作字符串。您需要自己对数组进行空终止,用作读取缓冲区,稍后用作字符串。

关于c - 从用户输入中读取句子的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100776/

相关文章:

c++ - 序列号 : write() throttling?

c - 从不同于 main 的不同文件中的函数返回指向字符数组的指针

c - 在 main() 中将指针分配给 NULL 后,for 循环不执行

c - 元音计数不正确

c++ - SSE 文档和访问

c - select() 中的 nfds 用于什么

c - 为什么 fgets 不能从 popen 流中获取所有字节

c - 本地指针存储在内存中的什么位置?

c - 使用 nc_create 写入压缩文件

c - 仅使用 "~ & ^ | + << >> ="个运算符和 20 个运算实现逻辑右移