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

时间:2017-01-21 04:22:33

标签: c

我使用下面的代码接收用户输入,然后将其与字符串exit进行比较,以便用户可以通过在命令行中键入来退出游戏。但是,除非我在*buffer的比较中使用exit,否则它无效。这样做是因为它指向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");
}

3 个答案:

答案 0 :(得分:1)

buffer != "exit" - &gt; (strcmp(buffer, "exit\n"))

答案 1 :(得分:0)

替换

while(buffer != "exit");

while(strcmpi(buffer, "exit"));

在C中,您无法使用==或!=运算符检查字符串的逻辑相等性。您需要使用&#39; strcmp&#39;等功能。或strcmpi

答案 2 :(得分:0)

如果将字符串与==进行比较,则只是比较字符串的基址,而不是字符串的实际内容。使用<string.h>中的strcmp来比较字符串。你的声明应该是这样的:

while (strcmp(buffer, "exit"));

注意:您还应该在代码中使用-Wall -Wextra进行编译,并且您会看到使用==来比较字符串的一些警告。

但是,由于getline在缓冲区的末尾添加\n,类似于fgets,您可能需要删除此\n字符。这将允许您的代码按预期工作。否则,您的代码实际上是这样做的:

while (strcmp("exit\n", "exit"));

在找到"exit"时不允许循环终止,因为strcmp()仅返回0相等的字符串。

您还需要使用getline()检查错误,因为如果无法读取一行,则会返回-1。在这种情况下,他们也不需要使用malloc()分配内存,因为getline()将缓冲区的地址存储在*buffer内。函数getline()基本上为你分配内存,所以在这种情况下自己做这将是多余的。说完这个,你需要在某个时候free()这个缓冲区。有关详细信息,请参阅此man page

考虑到这些要点,您可以像这样构建代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void ){
    char *buffer = NULL;
    size_t buffsize;
    ssize_t read = 0;
    const char *exits = "exit";

    while (1) {
        printf("Enter a command: ");

        read = getline(&buffer, &buffsize, stdin);
        if (read == -1) {
            printf("Failure found from getline()\n");
            exit(EXIT_FAILURE);
        }

        if (read > 0 && buffer[read-1] == '\n') {
            buffer[read-1] = '\0';
        }

        if (!*buffer || strcmp(buffer, exits) == 0) {
            break;
        }

        printf("%zu characters were read.\n", read);
        printf("You typed: '%s' \n", buffer);

        free(buffer);
        buffer = NULL;
    }

    return 0;
}