user6866732
user6866732

Reputation: 27

Why can't I type a string with space?

I'm currently practicing on struct, and here is my simple code. I'm currently having a problem here that I couldn't find the answer. My code asks me to type a song's name, its artist and duration of the song. I typed "My Lightning Speed", but only the word "My" fills the song's name. The word "Lightning" fill the artist and Speed fills the duration. Why? How can I fix it?

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#define SIZE 20

typedef struct {
    char name[SIZE];
    char artist[SIZE];
    int duration;
} songname;

songname FillSong();

int main()
{
    songname songNumb1, songNumb2, songNumb3;

    songNumb1 = FillSong();
    songNumb2 = FillSong();

    return 0;
}

songname FillSong()
{
    songname tempC;

    printf("\n");
    printf("Enter the name of this song: ");
    scanf(" %s", tempC.name);
    printf("name: %s\n", tempC.name);

    printf("Who is the artist? ");
    scanf(" %s", tempC.artist);
    printf("artist: %s\n", tempC.artist);

    printf("What is the duration(seconds)? ");
    scanf("%d", &tempC.duration);
    printf("duration: %d\n", tempC.duration);

    return tempC;
}

Upvotes: 0

Views: 1415

Answers (3)

Akash Mahapatra
Akash Mahapatra

Reputation: 3248

scanf skips the white space (blanks, tabs,newlines, etc.) while reading input. To read input whose format is not fixed, it is often best to read a line at a time.

Please read " The C programming Language" By Brian W. Kernighan and Dennis M. Ritchie to learn more.

Upvotes: 3

ganesh vicky
ganesh vicky

Reputation: 17

The scanf() funtion stops reading when a new line or a white space is detected if you want to enter a string with spaces try using gets() function.

Syntax: gets(variable name);

The gets function stops getting input only when a new line is entered.

Upvotes: 0

Hemant Pathak
Hemant Pathak

Reputation: 68

by default scanf will read first set on non whitespace characters. Consider reading an entire line of text for name of song or anything where there may be spaces in the name.

There may be some cases when you may want to have a comma or semicolon separated field, the expression given in https://stackoverflow.com/a/40568616/5675174 will help for such cases

Upvotes: 0

Related Questions