我正在使用下面的代码接收用户输入,然后将其与字符串 exit
进行比较,以便用户可以通过在命令行中输入该字符串来退出游戏。但是它不起作用,除非我在与 exit
的比较中使用 *buffer
。它这样做是因为它指向 exit
中的第一个字母。问题是这意味着任何以 e
开头的单词都会导致我的 while 循环退出。
#include<stdio.h>
#include<stdlib.h>
int input( char *s, int length);
int main(){
char *buffer;
size_t bufsize = 32;
size_t characters;
do{
buffer = (char *)malloc(bufsize * sizeof(char));
if(buffer == NULL){
perror("Unable to allocate buffer");
exit(1);
}
printf("Enter a command: ");
characters = getline(&buffer, &bufsize, stdin);
printf("%zu characters were read.\n", characters);
printf("You typed: '%s' \n",buffer);
}while(buffer != "exit");
}
最佳答案
buffer != "exit"
-> (strcmp(buffer, "exit\n"))
关于c - 使用 getline() 获取用户输入并在 while 循环中与另一个字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775705/