c - 如何阅读整个单词,而不仅仅是第一个字符?
问题描述
我正在用 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
}
}
解决方案
不要重复使用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;
}
推荐阅读
- linux - 在 ubuntu bash 脚本中,当我尝试转换错误的十六进制值时不会抛出任何错误
- python - SortBy 仅在“内部列表”中工作一半
- css - 动画迭代计数在 vuejs3 中不起作用?
- linux - elasticsearch 未启动 - 获取 java.lang.IllegalArgumentException:未能执行脚本
- next.js - Strapi,Next.js:无法在 /product 页面中加载产品(集合类型)并通过 id 打开产品
- reactjs - 如何从 React 中的其他组件调用组件中的函数?
- vba - 如何制作不可见的excel图表
- google-sheets - 使用日期时使用 Google 表格 ARRAYFORMULA + SUMIFS
- javascript - Reactjs:setTimeout 没有按预期工作
- javascript - 反转字符串连接