简体   繁体   English

使用C从用户输入中获取文本

[英]Get text from user input using C

I am just learning C and making a basic "hello, NAME" program. 我只是在学习C并制作一个基本的“hello,NAME”程序。 I have got it working to read the user's input but it is output as numbers and not what they enter? 我已经让它工作来读取用户的输入,但它输出为数字而不是它们输入的内容?

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;
}

You use the wrong format specifier %d - you should use %s . 您使用错误的格式说明符%d - 您应该使用%s Better still use fgets - scanf is not buffer safe. 更好的是仍然使用fgets - scanf不是缓冲区安全的。

Go through the documentations it should not be that difficult: 浏览文档不应该那么困难:

scanf and fgets scanffgets

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
#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;
}

When we take the input as a string from the user, %s is used. 当我们将输入作为用户的字符串时,使用%s And the address is given where the string to be stored. 并且给出了要存储的string的地址。

scanf("%s",name);
printf("%s",name);

hear name give you the base address of array name . 听到名字给你array 名称base address The value of name and &name would be equal but there is very much difference between them. name&name的值equal但它们之间存在很大差异。 name gives the base address of array and if you will calculate name+1 it will give you next address ie address of name[1] but if you perform &name+1 , it will be next address to the whole array . name给出arraybase address ,如果你计算name+1 ,它将给你next addressname[1]地址,但如果你执行&name+1 ,它将是whole array next address

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用于字符串和字符类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM