问题:编写一个程序,使用 getchar()
接收文本输入并输出字符串,删除多个空格。
这是我编写伪代码的方式:
While each input character is received before reaching EOF, do the following:
1) if character is non-blank, print it out
2) otherwise:
a. print out the blank
b. do nothing untill the next non-blank character
3) if a non-blank character is reached, go back to 1)
我尝试这样实现算法:
#include <stdio.h>
/* replaces multiple blanks with a single blank */
main(){
char c;
while((c= getchar())!=EOF){
if (c != ' ')
putchar(c);
else {
putchar(c);
while(c == ' ')
;
}
}
}
当字符串包含空格时,它会停止。我不确定我应该如何调试它。我认为问题出在我的第二个 while
上,程序在那里进入无限循环而不是等待新字符。
最佳答案
#include <stdio.h>
/* replaces multiple blanks with a single blank */
main(){
int c; // thanx chux
while((c= getchar())!=EOF){
if (c != ' ')
putchar(c);
else {
putchar(c);
while((c= getchar())!=EOF)
if (c!=' ')
{
putchar(c);
break;
}
}
}
}
你最后一次没有从 stdin 读取字符,导致无限循环比较上一个 getchar() 中的最后一个红色字符。
关于c - 在 C 中使用 putchar 和 getchar 删除多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205071/