is it possible to use fgets to store the userinput from a single line into 2 arrays?

Viewed 367

I'm trying to store the user input name into the structure. I am using fgets instead of scanf because I want to control the length of the user input. Is it possible to use fgets to store the user input from a single line separated by white space into 2 arrays (for my case it's the lastName[10] and firstName[10])?

Is the only way to use printf function in order to print 2 strings that are taken from the user by firstName and lastName individually?

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

struct names {
    char lastName[10];
    char firstName[10];
} names;

int main() {
    printf("Enter names (firstName lastName): \n");
    fgets(names.firstName, 10, stdin);
    fgets(names.lastName, 10, stdin);
    printf("first Name: %s last Name: %s \n", names.firstName, names.lastName);
    return 0;
}
3 Answers

The problem with the standard C functions in stdio.h is that they are easy to get wrong which may lead to buffer overflow. Here is a safe way to read the names using a custom function:

#include <ctype.h>
#include <stdio.h>

#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])

struct names {
    char lastName[10];
    char firstName[10];
} names;

void ReadName(char name[], int nameLen)
{
    int ch, i;

    /*skip whitespace*/
    do {
        ch = getchar();
    } while (isspace(ch));

    i = 0;
    while ((isgraph(ch) || ((unsigned char) ch >= 128)) && (i < nameLen - 1)) { /*accept any UTF-8 byte*/
        name[i] = ch;
        i++;
        ch = getchar();
    }
    name[i] = '\0';
}


int main(void)
{
    printf("Enter names (first name last name): \n");
    ReadName(names.firstName, LEN(names.firstName));
    ReadName(names.lastName, LEN(names.lastName));
    printf("First name: %s\nLast name: %s\n", names.firstName, names.lastName);
    return 0;
}

Edit: Made ReadName accept UTF-8 characters.

You can declare a character array as for example

char line[20];

(the size of the array can be greater than 20) and read data in this character array

fgets( line, sizeof( line ), stdin );

when you can use the function sscanf to read lastName and firstName like

sscanf( line, "%s %s", names.firstName, names.lastName );

Also by determining the position of a blank in line you can determine that each substring is not greater than 9 characters.

Actually, what you are trying to do (including controlling the length of the user input) is better accomplished using scanf:

scanf("%9s %9s",names.firstName,names.lastName);

The "%9s" limits each string to 9 characters (to avoid overflowing your strings), and the space in the format string scans for whitespace, so you can enter first and last names on a single input line.

Related