c - 我的用户输入在 C 中出现段错误

标签 c segmentation-fault fgets

所以我已经断断续续地阅读和练习 C 语言几个月了,最后我决定开始修改一些代码。所以我在谷歌上搜索了一些简单的程序来尝试编写,第一个程序是一个可以反转用户输入的程序。现在我不需要任何答案,但如果你能告诉我我是否使用了任何错误的函数或其他什么东西。

代码是:(为了调试忽略strlen的printf)

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

int main(int argc, char *argv[]) {

    char command[100];

    printf("please enter string: ");
    fgets(command, 100, stdin);

    //printf("%d", strlen(command));

    int ha = strlen(command);

    while(1){
        if(!strcmp(command,"quit")) {
            for(int i = 0; i < ha; i++) {
                int str = strlen(command) - i;
                puts(command[str]);
            }
        } else {
            exit(0); 
        }

        printf("please enter string: ");
        fgets(command, 100, stdin);
    }
    return 0;
}

它编译时没有警告或错误,但在输入一些输入后运行时,它会给我一个段错误。 非常感谢任何帮助!

最佳答案

段错误来自 put 函数。参数应该是 char* (puts (command))。

if 条件不会成立,因为 fgets 读取的是“quit\n”,您可以使用 strtok(c​​ommand,"\n") 删除该字符,也可以将\n 添加到 strcmp

我会尝试编译带有更多警告的代码,我也总是使用 -ansi -pedantic -Wall。

关于c - 我的用户输入在 C 中出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882486/

相关文章:

c - 什么决定了一个全局定义的字符串是在数据段的读写区还是只读区?

c - 在函数中传递指向 SOCKADDR_IN 和 SOCKET 的指针

c++ - 如何调试 C++ 段错误?

C文本游戏段错误及调试

c - 是什么导致调用 inb_p() 时出现段错误?

c - C中的重定向输入 : fgets() end of line "\n" interfering with strcmp()

c - 如何将结构的内容保存到 C 文件中?

c - 数组中唯一值的记录

c++ - FLTK:覆盖 FL_box 构造函数。 C++

c - 为什么它不调用 fgets?