我正在尝试使用我的函数从用户输入问题中读取句子,当我尝试调用它时它会跳过第二次尝试。有什么解决办法吗?
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()
函数中,
array
不是由malloc()
或 family 动态分配的内存。使用未分配内存的指针调用
free()
会动态创建未定义的行为。getchar()
返回一个int
。您应该将c
的类型更改为int c
。此外,
readString()
中的输入没有空值终止,因此您不能直接将数组用作字符串。您需要自己对数组进行空终止,用作读取缓冲区,稍后用作字符串。
关于c - 从用户输入中读取句子的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100776/