简体   繁体   中英

C string(char array): ignores next scanf because of spaces

say something like this:

#include <stdio.h>

void main() {

  char fname[30];
  char lname[30];

  printf("Type first name:\n");
  scanf("%s", fname);

  printf("Type last name:\n");
  scanf("%s", lname);

  printf("Your name is: %s %s\n", fname, lname);
}

if i type "asdas asdasdasd" for fname , it won't ask me to input something for lname anymore. I just want to ask how i could fix this, thank you.

Putting %s in a format list makes scanf() to read characters until a whitespace is found. Your input string contains a space so the first scanf() reads asdas only. Also scanf() is considered to be dangerous (think what will happen if you input more then 30 characters), that is why as indicated by others you should use fgets() .

Here is how you could do it:

#include <stdio.h>
#include <string.h>

int main()
{
    char fname[30];
    char lname[30];

    printf("Type first name:\n");
    fgets(fname, 30, stdin);

    /* we should trim newline if there is one */
    if (fname[strlen(fname) - 1] == '\n') {
        fname[strlen(fname) - 1] = '\0';
    }

    printf("Type last name:\n");
    fgets(lname, 20, stdin);
    /* again: we should trim newline if there is one */
    if (lname[strlen(lname) - 1] == '\n') {
        lname[strlen(lname) - 1] = '\0';
    }

    printf("Your name is: %s %s\n", fname, lname);

    return 0;
}

However this piece of code is still not complete. You still should check if fgets() has encountered some errors. Read more on fgets() here .

Use fgets (or getline if you are using GNU) to get an entire line instead of until the first whitespace.

if (fgets(fname, 30, stdin) == NULL) {
    // TODO: Read failed: handle this.
}

See it working online: ideone

You could also consider using the function fgets_wrapper from this answer as it will also remove the new line character for you.

change

scanf("%s", fname);

to

scanf("%[^\n]%*c", fname);

[^\\n] is accept other than '\\ n'

%*c is ignore one character('\\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM