c - 我的 C 程序出现意外输出和段错误

标签 c

我正在尝试学习编程,并尝试使用 C 编写以下代码。但是,正如您在下面看到的,我没有得到预期的输出,并且在尝试解决方案时遇到段错误:

我觉得我在名字或其他东西的声明上做错了。但无法弄清楚。

我的代码:

#include <stdio.h>

int main(void){
    char first_name;
    printf("Enter your name: \n");
    scanf("%c", &first_name);
    printf("Hello, %c", first_name);
}

实际输出

这是我当前得到的输出:

Enter your name: 
asdasfasf
Hello, a

预期输出

Enter your name: 
asdasfasf
Hello, asdasfasf

最佳答案

这是我的回答

#include <stdio.h>

int main(void){    
        char first_name[100] = {0}; 
        printf("Enter your name:(Max length is 99)\n"); 
        scanf("%99s", first_name); 
        printf("Hello, %s\n", first_name); 
}

运行会输出

Enter your name:(Max length is 99)
asdasfasf
Hello, asdasfasf

这是我的另一个解决方案,可以处理 @Andreas Wenzel 指出的“名字可能由多个单词组成”:

#include <stdio.h>

int main()
{
    char first_name[100] = {0};
    char c = 0;
    printf("Enter your name:(Max length is 99)\n");

    // read 99 times, once a character, it suspend when read '\n', 
    // otherwise save to first_name array  when read character.
    for(int m = 0; m < 99; m++){
        if((c = getchar()) != '\n'){
            first_name[m] = c;
        }else{
            break;
        }
    }

    printf("Hello, %s\n", first_name);
}

运行会输出

Enter your name:(Max length is 99)
asdsfd  
Hello, asdsfd

或者像这样:

Enter your name:(Max length is 99)
dsds dggffgg
Hello, dsds dggffgg

或者也像这样:

Enter your name:(Max length is 99)
ssd dsdfds dsfdfgfdg ddfdsfdf sfsdfsdf
Hello, ssd dsdfds dsfdfgfdg ddfdsfdf sfsdfsdf

关于c - 我的 C 程序出现意外输出和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76550574/

相关文章:

c - 如何使用 C 在 Ubuntu 上获取 WIFI 参数(带宽、延迟)

c++ - RAII 套接字 : when to release (close)

c - 内核土地套接字连接超时

c++ - 将 GNU 汇编程序编译到 Windows

c - 有没有一种简单的方法将值转换为字符串?

c - 使用指针将一个数组分配给另一个数组

将数组的内容转换为 C 中的算术类型

无需转换即可从有符号整数转换为无符号整数

C++ 类型 unsigned long int

检查 char 数组是否以特定字符开头