gpt4 book ai didi

c - 在 C 中处理用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:29 24 4
gpt4 key购买 nike

我试图在 C 程序的无限循环中读取用户输入。执行此操作的函数如下所示。

void processUserInput(unsigned int io, char* cmd, char* buffer){

char* usrInput;

int rbytes;
if ((rbytes = read(io, buffer, 256)) < 0) {
perror("Read error: ");
exit(-1);
}
buffer[rbytes-1] = 0;

usrInput = (char*) calloc(256, sizeof(char));
strcpy(usrInput, buffer);

cmd = strtok(usrInput, " ");
}

在我看来,这就是我所做的。

char buffer[256];
char* cmd = NULL;
processUserInput(STDIN_FILENO, cmd, buffer);

if(strcasecmp(cmd, "quit") == 0){

breakTrigger = 1;

}
memset(buffer, 0, 256);

当我在 STDIN 上输入一个输入时,代码给出了一个 segmentation fault。任何帮助表示赞赏。

最佳答案

因为cmd的参数类型。在 processUserInput 中,cmd 是一个指向 char(字符串)的指针,因此,您可以更改 cmd 指向的内容,但方法返回时 cmd 不会更改。您应该使用 &cmd 调用 processUserInput,并在 processUserInput 中执行 *cmd = strtok(...),或者更好的是,让 processUserInput 返回 cmd。

char* processUserInput(unsigned int io, char* buffer){

char* usrInput;

int rbytes;
if ((rbytes = read(io, buffer, 256)) < 0) {
perror("Read error: ");
exit(-1);
}
buffer[rbytes-1] = 0;

usrInput = (char*) calloc(256, sizeof(char));
strcpy(usrInput, buffer);

return strtok(usrInput, " ");
}

char buffer[256];
char* cmd = processUserInput(STDIN_FILENO, buffer);

关于c - 在 C 中处理用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com