0

As a beginner to code I'm following a free course on C, and currently trying to understand strings.

To test things out I've been writing the following :

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


int main()
{
    char test[] = "What's your name ?\n\n";
    char firstName[100];
    char lastName[100];

    printf("%s", test);

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

    printf("What's your last name ?\n");
    scanf("%s", lastName);

    printf("Your name is %s %s", firstName, lastName);


    return 0;
}

When I run it, the first printf() displays test[] normally.

The rest of the program works correctly ONLY IF there are no spaces in firstName or lastName.

If there's a space in firstName, the program will skip the second scanf and display firstName. If there are two spaces in firstName, the program will skip the second scanf and display only the first two words in firstName. If there's a space in lastName the program will display firstName and only the first word in lastName.

I don't understand why it does so, and especially why the second scanf gets skipped when there's a space in firstName. The first printf shows that spaces should be handled without issues so why does it malfunction when I use them with scanf ?

Thank you for your attention.

Nono Nunu
  • 3
  • 3
  • 3
    `scanf("%s", buffer);` is as [dangerous as `gets`](https://stackoverflow.com/q/1694036/2505965)! Always limit your inputs `scanf("%99s", buffer);` to the length of your buffer - 1. Better yet use [`fgets`](https://en.cppreference.com/w/c/io/fgets). – Oka Jul 27 '21 at 16:31
  • ... so it is impossible to input a string containing a space with `%s`. The `scanf` function is designed this way. Consider using `%[]` or `fgets`. – Weather Vane Jul 27 '21 at 16:38
  • If you want to read lines including spaces, don't use `scanf()` — use `fgets()` or POSIX `getline()` to read the line. Don't forget to zap the trailing newline that both those functions include with the data. – Jonathan Leffler Jul 27 '21 at 17:33

0 Answers0