Space in a String C

Asked

Viewed 5,307 times

1

I’m starting to learn C, and I came across the following doubt:

When I ask the user to inform me a song or artist, he ends up informing me a song with spaces, like "AS I AM", however the program skips the part of the music and the artist, how to solve this?

printf("MUSICA: "); 
scanf("%s", novo->nome);
printf("ARTISTA: "); 
scanf("%s", novo->artista);
printf("ANO: "); 
scanf("%d", &novo->ano);
  • typedef struct musica{ char nome[100]; char artista[100]; int ano; struct musica *Prox; }musica;

  • The answer has already solved your problem, I forgot to remove my comment.

1 answer

2


the scanf accepts several different structures to perform input values, and to capture an entire line, you must use a structure that reads up to a specific character.

char line[500];
scanf("%[^\n]",line);

The brackets "[" and "]", inform that you will have a condition, the " " indicates that you must collect everything that is typed until you reach " n".

  • 2

    Without specifying the size of the buffer in the format string, there is the risk of a buffer overflow. The correct for this example is scanf("%499[^\n]", line);

  • that I didn’t know, will be very useful to me.

  • 2

    @Gomiero is safer using the fgets in this case, fgets(line, sizeof(line), stdin) is a great way to avoid buffer overflow.

  • @Denercarvalho: Exact! It is always best to use the fgets to obtain a user input than the scanf :)

  • but if the variable is a char pointer, you wouldn’t be able to pick up the size through the sizeof and often use char pointers inside structs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.