Search code examples
cscanf

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


Solution

  • 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.