我正在嘗試為用戶輸入中的每個新“單詞”設定一個新變數,盡管他們輸入了多少單詞。例如,如果有人要鍵入red green blue,我想要變數 A=red、B=green 和 C=blue。到目前為止我嘗試過的是
char a[64];
char b[64];
char c[64];
scanf("%s%s%s", a, b, c);
printf("%s%s%s", a, b, c);
盡管它會掛起,直到用戶輸入三個單詞。我將如何解決這個問題?
真摯地,
NullUsxr
uj5u.com熱心網友回復:
如果您不知道需要存盤多少個單詞,那么您也不知道需要多少個變數。您不能將單詞存盤在單個變數中,將它們存盤在陣列中。
#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");
}
如果您想在一行上執行此操作,您可以使用它fgets來讀取該行并將strtok其分解為單詞(tokenize)。但是,同樣,您需要使用陣列。
這次我們不必為單詞分配空間,strtok而是使用它正在標記的字串的記憶體。我們只需要空間來存盤指向單詞的指標。
#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
}
實際程式使用諸如ncurses管理輸入和輸出的庫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464176.html
標籤:C
下一篇:類似宏的功能
