Marko
Marko

Reputation: 13

How to scan name and surname separated with space with scanf function in C without using loop and save it in one variable?

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

enter image description here

Upvotes: 0

Views: 270

Answers (2)

Marko
Marko

Reputation: 13

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

Upvotes: 0

chqrlie
chqrlie

Reputation: 144951

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.

Upvotes: 1

Related Questions