【发布时间】:2021-03-18 07:49:11
【问题描述】:
编辑:我后来发现这个问题主要源于我对 sizeof 的混淆,并将其替换为 strlen 几乎是我的解决方案。我的回答(向下滚动)提供了一个不错但简单的示例 strtok 如果您也有兴趣。
所以我一直在尝试让一个程序工作,在该程序中我输入一个用逗号分隔的单词列表,然后它会逐行输出这些单词,并删除所有空格。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define delim ","
int main() {
//variable declaration:
char words[100];
char *word;
char tempWord[100];
int n;
//gets input assinged to "words":
puts("\nEnter a list of words separated by commas.\n");
fgets(words, sizeof(words), stdin);
//sets up the first word in strtok
word = strtok(words, delim);
//loops so long as the word isn't null (reaching the last word)
while (word != NULL) {
puts("\n");
//checks if each character in the word is a space (and ignores them if they are)
for (n = 0; n < sizeof(word); ++n) {
//for some reason can't directly use word (probably because it's a pointer)
//so have to copy it to a temporary value
strcpy(tempWord, word);
//don't print if it's a space
if (!isspace(tempWord[n])) printf("%c", tempWord[n]);
}
//moves to next word
word = strtok(NULL, delim);
}
return(0);
}
通过输入“LETS, FREAKINGG, GOOOOOOOOOOOO”,我似乎遇到了一个问题:
(运行程序):
Enter a list of words separated by commas.
(input) >>>LETS, FREAKINGG, GOOOOOOOOOOOO
LETS
FREAKIN
GOOOOOO
似乎取决于第一个单词的大小,它将字符限制设置为不超过后续单词的 3 个字符。谁能解释为什么会这样?
【问题讨论】:
-
word是一个指针变量。sizeof(word)因此是指针的大小。它不是被指向的东西的大小,在编译时无法知道(sizeof是编译时运算符)。由于您似乎在地址为 64 位(8 字节)的平台上运行,因此此循环for (n = 0; n < sizeof(word); ++n)恰好迭代了 8 次,这就是您的话似乎被截断的原因。对于较短的单词,循环将溢出。 -
并添加到前面的评论 - 使用
strlen(word)而不是sizeof。其他问题:不需要strcpy进入另一个缓冲区,当然也不需要每次迭代。 -
tempWord和strcpy完全没有必要。即使它们很有用,在每个字符位置进行复制似乎也毫无意义,因为循环运行时word不会被更改。但是根本没有理由这样做,而且说有理由的评论是没有说服力的。最后,C 字符串以 NUL 字符(即 0)终止。因此,编写循环首先确定字符串的长度,然后迭代多次只是在做双重工作:除了搜索 NUL 之外,没有办法计算字符串的长度。循环,直到你命中 NUL。 -
@kaylum 谢谢!!我已经使用已解决的代码添加了对我自己的问题的答案。我并不太担心它缺乏效率,只是消除了我对 sizeof 的困惑有很大帮助。
标签: c string output size strtok