Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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.

like image 266
user974227 Avatar asked Dec 22 '22 05:12

user974227


1 Answers

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.

like image 66
Roman Byshko Avatar answered Dec 24 '22 02:12

Roman Byshko