c-在不使用库(除了stdio.h)的情况下,在换行符中打印每个单词的更好方法是什么



我正试图编写一个程序,从标准输入流中提取一个句子,并基于单词是"空格"之间的一切的定义;"空格"是空格字符、制表符或换行符,因此,例如,如果输入流是hey there this is some test,则输出应该是

hey
there
this
is
some
test

这是我的尝试:

#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define IS_SPACE(c) ((c) == ' ' || (c) == 't' || (c) == 'n')
int main() {
for(int c, inWord = FALSE; (c = getchar()) != EOF;)
if(!IS_SPACE(c)) {
putchar(c);
inWord = TRUE;
}
else if(inWord) {
putchar('n');
inWord = FALSE;
}
return 0;
}

但我不喜欢这种方法,因为当inWord = !IS_SPACE(c)可以自动完成时,我会手动向inWord输入TRUE和FALSE,但我不知道如何修改代码,只对IS_SPACE进行一次调用,而不创建另一个时态变量。

错误在于,如果文本以非空格结尾,则不会打印最后一个'\n'。或者这可能是一个功能?我没有修复它。

至于你的问题,你可以做

for(int c, inWord=FALSE; (c = getchar()) != EOF;) {
if(!IS_SPACE(c))
putchar(c);
else if(inWord)
putchar('n');
inword = !IS_SPACE(c);
}

甚至

for(int c, bPrevInWord = FALSE; (c = getchar()) != EOF;) {
int bInWord = !IS_SPACE(c);
if(bInWord)
putchar(c);
else if(bPrevInWord)
putchar('n');
bPrevInWord = bInWord;
}
int  my_spaces[256] = { 0 };
my_spaces[' '] = my_spaces['t'] = my_spaces['n'] = 1;
#define MY_SPACE(c) (my_sapces[c])

这是isspace()和朋友通常如何实现的核心,但使用isspace()isprint()、…的比特。。。。

编辑前的旧答案:看看strtok,尽管strtok_r现在是我选择的函数。构建到C中后,您可以期望它针对当前实现进行优化。

最新更新