我正在尝试学习编程,并尝试使用 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/