Removing multiple stubs using putchar and getchar in C
Problem: Write a program that receives text input with getchar()
and outputs a string by removing multiple spaces.
This is how I wrote the pseudocode:
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)
I tried to implement the algorithm as such:
#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 == ' ')
;
}
}
}
When the line contains spaces, it stops. I'm not sure how to debug it. I think the problem is with my second while
one and the program ends up in an infinite loop rather than waiting for new characters.
source to share
#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;
}
}
}
}
Lately, you haven't read characters from stdin by calling an endless loop comparing the last red character to the previous getchar ().
source to share
The anonymous answer works, but there is a simpler algorithm that also works:
While there is input remaining:
Read a character.
If the current and previous characters aren't both blank:
Print the current character.
In C:
#include <stdio.h>
int main() {
int prev = EOF, c;
while ((c = getchar()) != EOF) {
if (c != ' ' || prev != ' ')
putchar(c);
prev = c;
}
return 0;
}
source to share
Your program has several problems:
-
the prototype for
main()
must include the return typeint
. -
c
must be defined asint
so that you can correctly distinguishEOF
from all valid byte values โโreturnedgetchar()
. -
after you identify a blank character, you must continue reading characters and skip subsequent spaces.
-
technically blank characters include the space character
' '
and the tab character'\t'
. You must useisblank()
from<ctype.h>
and modify your program to skip subsequent blanks.
Here's a modified version:
#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;
}
source to share