从用户输入读取句子的function
我试图从我的function读取用户输入问题的句子是我尝试调用它时跳过第二次尝试。 有解决方案吗
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);
得到:
这是一句话|这是另一句话
你去:)
void readString(char *array, char * prompt, int size) { printf("%s", prompt); int c; int count=0; while((c = getchar()) != '\n' && c != EOF); while ((c = getchar()) != '\n') { array[count] = c; count++; if (count == (size - 1)) { break; } } array[count] = '\0'; }
在readString()
函数中,
-
malloc()
或family不会动态地为array
分配内存。使用未分配内存的指针调用
free()
会动态创建未定义的行为。 -
getchar()
返回一个int
。 您应该将c
的类型更改为int c
。 -
此外,
readString()
中的输入没有空终止,因此您无法直接将数组用作字符串 。 您需要自己对数组进行空终止,将其用作读缓冲区以便稍后用作字符串。