这是我的原始代码:
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
// program to print input one word per line
int main(void)
{
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
printf("\n");
}
else if (state == OUT) {
state = IN;
}
if (state == IN) {
putchar(c);
}
}
return 0;
}
但问题是如果有多个空格(空格)或多个制表符彼此相邻,则会为两者打印换行符。所以我使用了一个变量(last)来跟踪我在哪里:
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
// program to print input one word per line, corrected bug if there was
// more than one space between words to only print one \n
int main(void)
{
int c, last, state;
last = EOF;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (last != c) {
state = OUT;
printf("\n");
}
}
else if (state == OUT) {
state = IN;
}
if (state == IN) {
putchar(c);
}
last = c;
}
return 0;
}
那解决了它,除了现在如果 [blank][tab] 彼此相邻,则会为两者打印一个换行符。
有人可以帮忙吗?
最佳答案
原始代码的问题是您将为每个 空白字符输出换行符。您只想在从单词转换为非单词时执行此操作:
改变:
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
printf("\n");
}
到:
if (c == ' ' || c == '\n' || c == '\t') {
if (state == IN) printf("\n");
state = OUT;
}
事实上,我最初认为我建议的是按照以下方式对各州进行枚举:
enum eState {IN, OUT};
:
enum eState state = OUT;
但是,对于只有两个状态的简单有限状态机,您可以只使用 bool 值:
#include <stdio.h>
#define FALSE (1==0)
#define TRUE (1==1)
// Or: enum eBoolean {FALSE = 0, TRUE = 1};
int main (void) {
int ch;
int inWord = FALSE; // Or: enum eBoolean inWord = FALSE;
// Process every character.
while ((ch = getchar()) != EOF) {
// Check for whitespace.
if (ch == ' ' || ch == '\n' || ch == '\t') {
// Check if transitioning nonwhite to white.
if (inWord) {
printf("\n");
}
// Mark white no matter what.
inWord = FALSE;
} else {
// Mark non whitespace.
inWord = TRUE;
}
// If not whitespace, output character.
if (inWord) {
putchar(ch);
}
}
return 0;
}
关于C程序,换行符和制表符彼此相邻的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3974416/