这是我到目前为止的代码,我试图将多个空格和制表符替换为单个空格。输入是具有多个制表符和空格的多行(包括混合制表符和空格的句子)。写了这么多,我陷入困境:
#include <stdio.h>
#define NONBLANK 'a'
main(){
int c, lastc;
lastc = NONBLANK;
while (( c = getchar()) !=EOF) {
if (c != ' ' || lastc !=' '){
if (c != '\t' || lastc !='\t'){
putchar(c);
lastc = c;}
}
}
}
}
最佳答案
问题是 getchar()
在输入时回显输入,通过回显您想要压缩的空格和制表符来让您感到困惑。使用非回显 getch()
尝试此操作。我没有使用EOF
来结束,但是返回,随意尝试一下。
#include <stdio.h>
#include <conio.h>
int main(void)
{
int c, lastc = -1;
while ((c = getch()) != '\r') {
if (c != ' ' && c != '\t'){
if (lastc == ' ' || lastc == '\t')
putchar(' ');
putchar(c);
}
lastc = c;
}
return 0;
}
另请注意您对 main()
的错误声明。
关于c - 将每个由一个或多个空格和/或制表符组成的字符串替换为一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054142/