Home > Software engineering >  How to set variables in between spaces?
How to set variables in between spaces?

Time:04-26

I'm trying to set a new variable for each new "word" in a user input, despite how many words they type. For example, if someone were to type red green blue, I'd want variable A=red, B=green, and C=blue. What I've tried so far is

char a[64];
char b[64];
char c[64];
scanf("%s%s%s", a, b, c);
printf("%s%s%s", a, b, c);

Although it hangs until the user inputs three words. How would I go about resolving this?

Sincerely,

NullUsxr

CodePudding user response:

If you don't know how many words you need to store, you also don't know how many variables you'll need. You can't store the words in individual variables, store them in an array.

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

#define MAX_WORDS 64
#define MAX_WORD_LEN 64

int main()
{
    // Allocate space for 64 words of 64 characters, plus the null byte.
    // Initialize the array to 0.
    char words[MAX_WORDS][MAX_WORD_LEN 1] = {{0}};
    
    // Loop until you see the max words you can.
    for(int i = 0; i < MAX_WORDS; i  ) {
        printf("word? ");
        
        // If they don't input a word, stop looping.
        // They'll have to hit ctrl-d to end input.
        if( scanf("ds", words[i]) < 1 ) {
            break;
        }
    }

    // Print the words.
    // Loop either up to the max, or until a NULL.
    for(int i = 0; words[i] && i < MAX_WORDS; i  ) {
        printf("%s ", words[i]);
    }
    printf("\n");
}

If you want to do this on a single line you can use fgets to read the line and strtok to break it up into words (tokenize). But, again, you'll need to use an array.

This time we don't have to allocate space for the words, strtok uses the memory of the string it is tokenizing. We only need space to store pointers to the words.

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

#define MAX_WORDS 64

int main()
{
    // Allocate space for 64 words.
    // Initialize the array to 0.
    char *words[MAX_WORDS] = {0};

    // Read a line.
    char line[BUFSIZ];
    fgets(line, sizeof(line), stdin);

    char *word;
    int i;
    for(
        // Get the first word.
        word = strtok(line, " "), i = 0;
        // Stop when there are no more words
        // Or you're out of space to store them.
        word != NULL && i < MAX_WORDS;
        // Continue to break the line into words.
        word = strtok(NULL, " "), i  
    ) {
        words[i] = word;
    }

    // the rest is the same
}

Real programs use a library such as ncurses to manage input and output.

  •  Tags:  
  • c
  • Related