[英]Removing multiple blanks using putchar and getchar in C
问题:编写一个程序,使用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读取字符,导致infinie循环比较前一个getchar()的最后一个红色字符。
匿名的答案有效,但有一个更简单的算法也可以工作:
While there is input remaining:
Read a character.
If the current and previous characters aren't both blank:
Print the current character.
在C:
#include <stdio.h>
int main() {
int prev = EOF, c;
while ((c = getchar()) != EOF) {
if (c != ' ' || prev != ' ')
putchar(c);
prev = c;
}
return 0;
}
#include <stdio.h>
int main(void){
int c;
while((c = getchar())!=EOF){
if (c != ' ')
putchar(c);
else {
putchar(c);
while((c = getchar()) == ' ')
;
ungetc(c, stdin);//go back 1
}
}
return 0;
}
这对我有用。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
int space = 0;
while ((c = getchar())!= EOF){
if (c != ' '){
putchar(c);
}else{
if(space == ' '){
continue;
}else{
putchar(c);
}
}
space = c;
}
return 0;
}
您的计划有一些问题:
main()
的原型必须包含返回类型int
。
c
必须定义为int
这样才能正确区分EOF
和getchar()
返回的所有有效字节值。
识别出空白字符后,必须继续读取字符并跳过后续空白。
从技术上讲,空白字符包括空格字符' '
和制表符'\\t'
。 您应该使用<ctype.h>
isblank()
并修改您的程序以跳过后续的空白字符。
这是一个修改版本:
#include <ctype.h>
#include <stdio.h>
/* replaces multiple blanks with a single blank */
int main(void) {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
if (isblank(c)) {
while (isblank(c = getchar())
continue;
if (c == EOF)
break;
putchar(c);
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.