首页 > 解决方案 > 如何阅读整个单词,而不仅仅是第一个字符?

问题描述

我正在用 C 语言编写一个方法,其中我有一个从标准输入重定向的文件中的单词列表。但是,当我尝试将单词读入数组时,我的代码只会输出第一个字符。我知道这是因为 char 和 char * 的转换问题。

虽然我挑战自己不要使用 string.h 中的任何函数,但我尝试迭代并正在考虑编写自己的 strcpy 函数,但我很困惑,因为我的输入来自我从标准重定向的文件输入。该变量numwords由用户在 main 方法(未显示)中输入。

我试图通过dumpwptrs向我展示输出是什么来调试这个问题。我不确定代码中的什么导致我得到错误的输出 - 无论是我如何将单词读入块数组,还是我用 wptrs 错误地指向它?

//A huge chunk of memory that stores the null-terminated words contiguously
char chunk[MEMSIZE]; 

//Points to words that reside inside of chunk
char *wptrs[MAX_WORDS]; 

/** Total number of words in the dictionary */
int numwords;
.
.
.
void readwords()
{
  //Read in words and store them in chunk array
  for (int i = 0; i < numwords; i++) {
    //When you use scanf with '%s', it will read until it hits
    //a whitespace
    scanf("%s", &chunk[i]);
    //Each entry in wptrs array should point to the next word 
    //stored in chunk
    wptrs[i] = &chunk[i]; //Assign address of entry
  }
}

标签: carraysstringiochar

解决方案


不要重复使用char chunk[MEMSIZE];用于先前的单词。

而是使用下一个未使用的内存。

char chunk[MEMSIZE]; 
char *pool = chunk; // location of unassigned memory pool

    // scanf("%s", &chunk[i]);
    // wptrs[i] = &chunk[i];
    scanf("%s", pool);
    wptrs[i] = pool;
    pool += strlen(pool) + 1;  // Beginning of next unassigned memory

健壮的代码会检查返回值scanf()并确保i, chunk不超过限制。

fgets()只要一次输入一行单词,我就会寻求解决方案。

char chunk[MEMSIZE]; 
char *pool = chunk;

// return word count
int readwords2() {
  int word_count;
  // limit words to MAX_WORDS
  for (word_count = 0; word_count < MAX_WORDS; word_count++) {
    intptr_t remaining = &chunk[MEMSIZE] - pool;
    if (remaining < 2) {
      break; // out of useful pool memory
    }
    if (fgets(pool, remaining, stdin) == NULL) {
      break; // end-of-file/error
    }
    pool[strcspn(pool, "\n")] = '\0'; // lop off potential \n
    wptrs[word_count] = pool;
    pool += strlen(pool) + 1;
  }
  return word_count;
}

推荐阅读