C string (char array): ignores next scanf due to 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 will no longer ask me to enter something for lname . I just want to ask how I can fix this, thanks.

+4
source share
3 answers

Use fgets (or getline if you are using GNU) to get the whole line, not before the first space.

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

See how it works on the Internet: ideone

You can also use the fgets_wrapper function from this answer , as it will also remove the newline character for you.

+4
source

Inserting %s in the list of formats allows scanf() to read characters until a space is found. Your input line contains a space, so the first scanf() reads only asdas . In addition, scanf() is considered dangerous (think what happens if you enter more than 30 characters), so as others have indicated, 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 not yet complete. You should still check if fgets() encountered some errors. Read more about fgets() here .

+5
source

change

 scanf("%s", fname); 

to

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

[^ \ n] takes a different value than '\ n'

% * c ignores one character ('\ n')

+1
source

Source: https://habr.com/ru/post/1384597/


All Articles