[Solved] How do I assign multiple words in one string to individual independent variables?


If the goal is to break a string containing two words into two strings, then the solution is simple. You can use fgets() to get a line of input, and sscanf() to store the two strings in appropriate variables. Note that the buffer that receives input from fgets() is generously sized to reduce the possibility of buffer overflow. Also note that a maximum width should always be specified when using the %s conversion specifier to avoid buffer overflows. You should always check the value returned by the scanf() family of functions; here the return value is used to prompt the user to enter input again if not enough information is given.

#include <stdio.h>

#define BUFF_SZ  1000
#define NAME_SZ  50

int main(void)
{
    char firstname[NAME_SZ];
    char lastname[NAME_SZ];

    char buffer[1000];
    printf("Input Full Name: ");
    fgets(buffer, sizeof buffer, stdin);

    while (sscanf(buffer, "%49s %49s",
                  firstname, lastname) != 2) {
        printf("Please enter a first and a last name: ");
        fgets(buffer, sizeof buffer, stdin);
    }

    printf("Hello, %s %s\n", firstname, lastname);

    return 0;
}

If there is a possibility of a first, middle, and last name, this code can be modified to act accordingly. Here, the value returned by sscanf() is stored in res. If it is not 2 or 3, the user is prompted to enter again. If the value returned was 2, no last name was entered, so the string stored in middlename is copied to lastname, and middlename is changed to an empty string.

Note that this code is a little more complicated, and now the string.h header file has been included for the strcpy() function prototype.

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

#define BUFF_SZ  1000
#define NAME_SZ  50

int main(void)
{
    char firstname[NAME_SZ];
    char middlename[NAME_SZ];
    char lastname[NAME_SZ];

    char buffer[1000];
    printf("Input Full Name: ");
    fgets(buffer, sizeof buffer, stdin);

    int res;
    while ((res = sscanf(buffer, "%49s %49s %49s",
                         firstname, middlename, lastname)) != 2 && res != 3) {
        printf("Please enter at least first and last name: ");
        fgets(buffer, sizeof buffer, stdin);
    }

    if (res == 2) {
        strcpy(lastname, middlename);
        middlename[0] = '\0';
    }

    printf("Hello, %s ", firstname);
    if (middlename[0] != '\0') {
        printf("%s ", middlename);
    }
    printf("%s\n", lastname);

    return 0;
}

For more uncertain requirements, strtok() may be needed to break the input string into tokens. Here an array of pointers to char is declared. This needs to be large enough to hold pointers to all of the words in the string, and may need to be dynamically allocated in some instances.

Here, strdup() is used to create a duplicate of the token returned by strtok(). Memory is allocated by the strdup() function, and it is the caller’s responsibility to free it before program termination. Note that strdup() is not in the C Standard Library, but it is POSIX, and quite common. The first line of this program is a feature test macro that may be needed to enable use of this function. Also note that the stdlib.h header file has been included for the free() function prototype.

In all of these examples, the value returned from fgets() should also be checked, and in the last example it is. If there is an error in fgets() a message is printed and the program exits.

#define _POSIX_C_SOURCE 200809L

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

#define BUFF_SZ    1000
#define MAX_WORDS  1000

int main(void)
{
    char buffer[1000];
    printf("Enter a string of words:\n");
    if (fgets(buffer, sizeof buffer, stdin) == NULL) {
        fprintf(stderr, "Error in fgets()\n");
        exit(EXIT_FAILURE);
    }

    char *token;
    char *words[MAX_WORDS];
    char *delims = " \t\r\n";
    size_t counter = 0;

    token = strtok(buffer, delims);
    while (token != NULL) {
        words[counter] = strdup(token);
        ++counter;
        token = strtok(NULL, delims);
    }

    for (size_t i = 0; i < counter; i++) {
        puts(words[i]);
    }

    /* Free allocated memory */
    for (size_t i = 0; i < counter; i++) {
        free(words[i]);
    }

    return 0;
}

Update

OP has mentioned a lack of familiarity with fgets() in comments, and that Get_String() is the function being used to get a line of input. Get_String() is not a standard C function. From the context, I suspect that this function returns a pointer to char, and that the function allocates memory for the string. If this is the case, these allocations will need to be freed before program termination.

It should be relatively simple to modify the above examples to use GetString(), though I would strongly suggest learning about fgets(). If string is an alias for char *, as I suspect, then you can’t simply declare string firstname;, since this allocates no memory for the string. So, you will need to declare arrays to hold the first name and the last name. I don’t guarantee this code, because I don’t have access to the function GetString(), but the first example could probably be rewritten as:

#include <stdio.h>

#define NAME_SZ  50

int main(void)
{
    char firstname[NAME_SZ];
    char lastname[NAME_SZ];

    string buffer;
    printf("Input Full Name: ");
    buffer = GetString();

    while (sscanf(buffer, "%49s %49s",
                  firstname, lastname) != 2) {
        printf("Please enter a first and a last name: ");
        free(buffer);
        buffer = GetString();
    }

    printf("Hello, %s %s\n", firstname, lastname);

    free(buffer);
    return 0;
}

Note that buffer is freed before the end of the program. Also note that buffer is freed if input is incorrect and more input is needed. In this case, calling GetString() allocates new memory for buffer, so the old memory must be freed first. This added complexity is one reason to avoid such type aliases as string. The device of using string in place of char * is considered by some to be useful for teaching, but I disagree; it makes actually using strings needlessly complex and confusing. Better to learn the way that actual code is written.

5

solved How do I assign multiple words in one string to individual independent variables?