C语言 使用 C 从用户输入中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22065675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text from user input using C
提问by Callum Whyte
I am just learning C and making a basic "hello, NAME" program. I have got it working to read the user's input but it is output as numbers and not what they enter?
我只是在学习 C 并制作一个基本的“你好,NAME”程序。我已经让它工作来读取用户的输入,但它输出为数字而不是他们输入的内容?
What am I doing wrong?
我究竟做错了什么?
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%d", &name);
printf("Hi there, %d", name);
getchar();
return 0;
}
回答by Sadique
You use the wrong format specifier %d- you should use %s. Better still use fgets - scanf is not buffer safe.
您使用了错误的格式说明符%d- 您应该使用%s. 最好还是使用 fgets - scanf 不是缓冲区安全的。
Go through the documentations it should not be that difficult:
查看文档应该不难:
Sample code:
示例代码:
#include <stdio.h>
int main(void)
{
char name[20];
printf("Hello. What's your name?\n");
//scanf("%s", &name); - deprecated
fgets(name,20,stdin);
printf("Hi there, %s", name);
return 0;
}
Input:
输入:
The Name is Stackoverflow
Output:
输出:
Hello. What's your name?
Hi there, The Name is Stackov
回答by MONTYHS
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", name);
printf("Hi there, %s", name);
getchar();
return 0;
}
回答by Rahul
When we take the input as a string from the user, %sis used. And the address is given where the stringto be stored.
当我们将输入作为来自用户的字符串时,%s使用。并给出了string要存储的地址。
scanf("%s",name);
printf("%s",name);
hear name give you the base addressof arrayname. The value of nameand &namewould be equalbut there is very much difference between them. namegives the base addressof arrayand if you will calculate name+1it will give you next addressi.e. address of name[1]but if you perform &name+1, it will be next addressto the whole array.
听到名字给你base address的array名字。name和&namewill的值equal但是它们之间有很大的区别。name给出base address的array,如果你会计算name+1它会给你next address的IE浏览器的地址name[1],但如果执行&name+1,这将是next address对whole array。
回答by user3359601
change your code to:
将您的代码更改为:
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", &name);
printf("Hi there, %s", name);
getchar();
getch(); //To wait until you press a key and then exit the application
return 0;
}
This is because, %d is used for integer datatypes and %s and %c are used for string and character types
这是因为 %d 用于整数数据类型而 %s 和 %c 用于字符串和字符类型

