C - scanf,printf name and age program [closed]

2020-04-12 09:44发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 5 years ago.

#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..

回答1:

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

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

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


回答2:

Name should be a chracter array, I mean string. So you can creat a string such:

char yourname[30];
.
.
scanf("%s", &yourname);
.
.
printf("your name is %s\n",yourname);


回答3:

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] = '\0';
    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);
}