[source code] C Programming Tutorial - 11 - Getting Input with scanf

+2 Bucky Roberts · August 4, 2014



#include <stdio.h>
#include <stdlib.h>

int main()
{
    char firstName[20];
    char crush[20];
    int numberOfBabies;

    printf("What is your name? \n");
    scanf("%s", firstName);

    printf("Who are you going to marry? \n");
    //scanf() stops when it sees a space, so no last names
    scanf("%s", crush);

    printf("How many kids will you have? \n");
    //ampersand needed for everything but arrays
    scanf("%d", &numberOfBabies);

    printf("%s and %s are in love and will have %d babies", firstName, crush, numberOfBabies);

    return 0;
}


Post a Reply

Replies

Oldest  Newest  Rating
0 Ass Cold · October 13, 2014
Hi bucky, can you show me how to make the program scan spaces? 
This is what I did, but is not working.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char firstName[20];
    char lastName[20];
    char crushFirstName[20];
    char crushLastName[20];
    int numberOfBabies;

    printf("What is your name?\n");
    scanf("%s and %s", firstName, lastName);

    printf("Who are you going to marry?\n");
    scanf("%s and %s", crushFirstName, crushLastName);

    printf("How many kids will you have?\n");
    scanf("%d", &numberOfBabies);

     printf("%s and %s are in love and will have %d babies", firstName, lastName, crushFirstName, crushLastName, numberOfBabies);

    return 0;
+2 Горан Куга · October 14, 2014
Hey buddy so this is how i would do it. User will have to enter firstName and lastName.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char firstName[20];
    char lastName[20];
    char crushFirstName[20];
    char crushLastName[20];
    int numberOfBabies;

    printf("What is your name? \n");
    scanf(" %s %s", firstName, lastName); // you don't need and between %s and %s just put a space between them.

    printf("Who are you going to marry? \n");
    scanf(" %s %s", crushFirstName, crushLastName); // same goes here as above.

    printf("How many kids will you have? \n");
    scanf(" %d", &numberOfBabies);

    printf("%s %s and %s %s are in love and will have %d babies. \n", firstName, lastName, crushFirstName, crushLastName, numberOfBabies); // here you need to use twice %s %s for firstName and lastName same for crushFirstName and crushLastName.

   system("pause") // this line is saying to our computer to pause after execute.
   return 0;
}
  • 1

C

126,397 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator