0
Follow
2
View

How to set variables in between spaces?

duanhongqing 注册会员
2023-01-26 03:57

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 
#include 
#include 

#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("%64s", 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 
#include 
#include 

#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.

About the Author

Question Info

Publish Time
2023-01-26 03:57
Update Time
2023-01-26 03:57