C语言 C - scanf,printf 名称和年龄程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26790111/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:32:16  来源:igfitidea点击:

C - scanf,printf name and age program

cprintfscanf

提问by Spiros Kmaris

#include <stdio.h>

int main ()
{
   char yourname;
   int yourage;

    printf("Whats your name?\t");
    scanf("%c",&yourname); 
    printf("How old are you?\t");
    scanf("%d",&yourage);
    printf("You are %d years old and your name is %c\n\n\n",yourage,yourname);
    system("pause");
    return(0);
}

I want this program to ask for the username and age, and then print them..

我想让这个程序询问用户名和年龄,然后打印出来。

采纳答案by crashxxl

when you use scanf, %cis intended to get a single character. If you want to get a string, you need to use %s.

当您使用scanf,时,%c旨在获取单个字符。如果要获取字符串,则需要使用%s.

Also, in C langage, string are just char arrays. So you need to declare a char array.

此外,在 C 语言中,字符串只是字符数组。所以你需要声明一个char数组。

#include <stdio.h>

int main ()
{
   char yourname[100];
   int yourage;

   printf("Whats your name?\t");
   scanf("%s",yourname); //i let you read the doc to avoid overflow :)
   printf("How old are you?\t");
   scanf("%d",&yourage);
   printf("You are %d years old and your name is %s \n\n\n",yourage,yourname);
   system("pause");
   return(0);
}

回答by Rizier123

This should work for you:

这应该适合你:

#include <stdio.h>

int main () {
   char yourname[20];
   int yourage;

    printf("Whats your name?\t");
    scanf("%18[^\n]s", yourname);

    yourname[19] = '##代码##';
    fflush(stdin);

    printf("How old are you?\t");
    scanf(" %d",&yourage);

    printf("You are %d years old and your name is %s\n\n\n", yourage, yourname);

    system("pause");
    return(0);
}