c - 使用 getline() 获取用户输入并在 while 循环中与另一个字符串进行比较

标签 c

我正在使用下面的代码接收用户输入,然后将其与字符串 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/

相关文章:

c - 再次自动运行 C 代码

c - 为什么用 C 编写的程序不能在 Windows 上运行?

c - 为什么 GCC 填充这个位域?

常量字符串的不区分大小写的比较

c - 在Raspberry PI3上测试kaa沙箱的NotificationDemo时出现段错误(核心转储)

c - 网络掩码转换,有什么问题?

c++ - 将文件扩展名从 c 更改为 cpp 后,如何解决 C++ 中的歧义错误?

c++ - sip调用中主叫和被叫如何共享RTP的ssrc值?

c - 使用指针替换值

c++ - 两个具有相同代码的共享对象(.so)文件的一致性如何