0

I tried using %[] but VSC immediately paint the % red and report an error.

enter image description here

Marko
  • 13
  • 5
  • 2
    `scanf("%s %s", name, surname)`? Or do you mean store them into a single variable? It would help if you gave a complete [mre] as well as the expected result vs actual result. Please take the [tour] and read [ask]. – kaylum Jan 27 '22 at 22:15
  • 1
    A decent rule is: if you're just starting out with `scanf`, don't use `%[]`. Scanf's virtue is that it is nice and simple, but `%[]` is not simple. Unless the name and surname will contain a space, you don't need `%[]`. If you're doing something complicated enough that you actually do need `%[]`, it means (IMO) that it's time to learn [how to use something better than `scanf`](https://stackoverflow.com/questions/58403537). – Steve Summit Jan 27 '22 at 23:18

2 Answers2

1

You can use scanf() to read a string with embedded spaces this way:

char fullname[100];

if (scanf("%99[^\n]", fullname) == 1) {
    printf("The full name is: %s\n", fullname);
} else {
    // either end of file was reached, scanf returned EOF
    // or no character was typed before the newline
    printf("input error\n");
}
// read and discard the rest of the line
scanf("%*[^\n]");  // discard the remaining characters if any
scanf("%*1[\n]");  // discard the newline if any

The reason Visual Studio Code shows an error is the syntax %[] is invalid. You cannot specify an empty set. The ] just after the %[ is interpreted as a ] character and there must be another ] to close the set as in %[]].

scanf() is full of quirks and pitfalls: it seems easier and safer to use fgets() or getline() to read a line of input and then perform explicit clean up of the string read from the user, such as removing the initial and trailing whitespace, which requires a loop in most cases.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

At the end, i concluded that program works fine and VSC painted '%' red for no reason. Thanks for your answers, they were useful.

Marko
  • 13
  • 5