C programming, Can anyone explain this? - c

#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
if (c == '\t')
printf("\\t");
else if (c == '\b')
printf("\\b");
else if (c == '\\')
printf("\\\\");
else
putchar(c);
}
return 0;
}
In this case for an input of
hi how are you\doing
I get an output
hi\thow\tare\tyou\\doing
#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
if (c == '\t') {
c = '\b';
printf("\\t");
}
if (c == '\b') {
c = '\b';
printf("\\b");
}
if (c == '\\') {
c = '\b';
printf("\\\\");
}
putchar(c);
}
return 0;
}
When I run this program with an input
hi how are you\doing
(The large spaces being tabs)
I get this output
hi\t\how\t\are\t\you\doing
Code:
#include <stdio.h>
int main() {
int c;
c = '\b';
putchar(c);
return 0;
}
On running this,
I get nothing. No output. Back to the shell prompt.
To be more precise, in the first program I get the output I want, but in the second program I get the backslashes after every \t but not after the \ I would expect \\\ to be the output looking at how \t became \t\, is '\b' causing it? if it is, how does it work? but if so why doesn't the same happen in the third program?
Ran this on rasbian default gcc compiler and mingw msys-gcc package for windows.

The reason the second program is behaving that way is because you are entering more than one if block:
if (c == '\t') {
c = '\b';
printf("\\t");
}
if (c == '\b') {
c = '\b';
printf("\\b");
}
if (c == '\\') {
c = '\b';
printf("\\\\");
}
putchar(c);
When you encounter a tab, the first block is entered where it prints \t to the screen then changes c to a backspace.
The second block is then entered because c is a backspace (because you just changed it to be that). That block then prints \b to the screen, so now you have \t\b on the screen.
When you then call putchar to write the backspace, the b will get overwritten by the next character. So when the next character is written you then have \t\ on the screen.
So the problem here is that you're testing c multiple times and potentially changing it in between. The reason this happens only with the tab is because you check for the tab first, then the backspace, then the backslash.
If you use else if instead of if, you won't enter multiple blocks:
if (c == '\t') {
c = '\b';
printf("\\t");
}
else if (c == '\b') {
c = '\b';
printf("\\b");
}
else if (c == '\\') {
c = '\b';
printf("\\\\");
}
putchar(c);
With this change, given the original input, the output will be:
hi\how\are\you\doing

Related

Understanding EOF and break

I am trying to write a program which replaces a string of one or more tabs by a single tab.
Here's what I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
while ((c = getchar()) != '\n')
{
if (c == 9)
{
while((c=getchar())== 9)
putchar(' ');
if (c != 9)
break;
}
putchar(c);
}
}
I compared it to newline because I don't get EOF and pressing ctrl-z does nothing, atleast on Windows.
Well the output prints spaces instead of tabs. Can someone point out what am I doing wrong?
There is no need to break, in fact, when you use break inside a for/while you exit from the loop (not what you want), if you want to allow only one tab use a sentinel and continue if the previous character is also a tab:
int c, tab = 0;
while (((c = getchar()) != '\n') && (c != EOF)) {
if (c == '\t') {
if (tab == 1) continue;
tab = 1;
} else {
tab = 0;
}
putchar(c);
}
Press CTRL+ Z + Intro to send EOF in Windows.
its because you write putchar(' ').
its an error. write putchar('\t') instead.
there is no such char as ' '. this is 4 spaces.

C - Why substracting single characters leave a blank?

I tried to replace characters with substraction. It works but it leaves a blank with this method:
#include <stdio.h>
int main(void) {
int c;
while((c = getchar()) != EOF) {
if (c == '\t')
putchar('t');
if(c == '\t')
c = c - '\t';
putchar(c);
}
}
Its the substraction that gives the unwanted output and I couldn't figure out why.
Example input:
Hello tab tab tab
Output:
Hello tabt tabt tab
Goal is Hello tabttabttab.
The "blank" is the result of printing NUL (0) character. Whenever you input '\t', you are printing NUL, which is not a printable character.
if(c == '\t')
c = c - '\t';
putchar(c); // same as putchar(0); if c == '\t'
Perhaps, you wanted to replace tabs with -:
if(c == '\t')
c = '-';
putchar(c);

Understanding putchar loop

This code takes multiple fs and prints only 1. Can someone please explain to me why this code does not print two fs? putchar appears twice while not EOF. I have been staring at it for hours and I do not understand how it prints only 1 f.
The code is functioning correctly. I just do not understand how it works step by step.
/* A program that takes input of varied 'f's and out puts 1 f */
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF)
{
if (c == 'f')
{
putchar(c);
}
while (c == 'f')
{
c = getchar();
}
if (c != EOF) putchar(c);
}
}
Thanks
I'll step through with comments in the code; for f (or in reality f\n) as input:
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) // You type f and hit return key (remember this)
{
if (c == 'f') // c contains 'f' is true
{
putchar(c); // print 'f'
}
while (c == 'f') // c == 'f' is true
{
c = getchar(); // '\n' is buffered on stdin from return key
// so getchar() returns '\n'. So c will be set to '\n'
// It goes back to the while loop and checks if c == 'f'
// but it's not, it's '\n'! So this will run once only.
}
if (c != EOF) putchar(c); // '\n' != EOF, so print '\n' newline, back to loop
}
}
Thus giving f\n as input will yield the output f\n
In the case of input fffff (in reality fffff\n), see below:
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) // You type fffff and hit return key
{
if (c == 'f') // c contains 'f' is true, first 'f'
{
putchar(c); // print 'f'
}
while (c == 'f') // First loop, c == 'f'
// Second loop, c == 'f'
// Last loop, c == '\n', so false
{
c = getchar(); // First loop: 'ffff\n' is still buffered on stdin
// c = 'f', loop again
// Last loop: c = '\n'
}
if (c != EOF) putchar(c); // '\n' != EOF, so print '\n' newline, back to loop
}
}
You see that your inner while loop will eat all the f until you hit \n, thus the same affect as above.
if(c == 'f')
putchar(c);
This prints one f, the one you see.
while(c == 'f')
getchar(c);
This is where the f disappears. If you just used putchar(c) before, that means that the loop will execute at least once because c == f. So the f is gone (c != f)
Finally, you just use putchar(c) on the first character which is not f.

The C Programming Language, Ch.1 Exercise 1.10 (Getchar and Putchar)

I've been working on this for 2 hours and I am stuck... I found the answer online, but that isn't going to help me learn the concept that I'm obviously missing.
Prompt: Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way.
Here's what I came up with, it doesn't replace a tab or \ with the indicated putchar, it just adds it in front of it.(I didn't do backspace because I can't really input a backspace...):
This is how I read the code. What am I missing?:
"There is some integer c. c is equal to the input. When the input is not equal to end of file proceed. If input is tab then the output \t. If input is \ then output \\. Output the input to console."
int c;
while((c=getchar())!=EOF)
{
if(c=='\t')
{
putchar('\\');
putchar('t');
}
if(c=='\\')
{
putchar('\\');
putchar('\\');
}
putchar(c);
}
Your main problem is that you are outputting the character regardless of the fact that you may have already output its translation. Those if statements will do what you expect but, in their present form, they simply drop through to the next statement.
Hence you'd be looking for something more like this:
while ((c = getchar()) != EOF) {
// Detect/translate special characters.
if (c == '\t') {
putchar ('\\');
putchar ('t');
continue; // Go get next character.
}
if (c == '\b') {
putchar ('\\');
putchar ('b');
continue; // Go get next character.
}
if (c == '\\') {
putchar ('\\');
putchar ('\\');
continue; // Go get next character.
}
// Non-special, just echo it.
putchar (c);
}
Another possibility, shorter and more succinct would be:
while ((c = getchar()) != EOF) {
// Detect/translate special characters, otherwise output as is.
switch (c) {
case '\t': putchar ('\\'); putchar ('t'); break;
case '\b': putchar ('\\'); putchar ('b'); break;
case '\\': putchar ('\\'); putchar ('\\'); break;
default: putchar (c);
}
}
I know im late to the party, but this question pops up in chapter one before else, case, continue, and functions are introduced.
Here is a working solution to exercise 1-10 that involves only concepts introduced up to the point of the exercise. You need to keep track of whether an escaped character was found and then display the copied character only if one was not found.
#include <stdio.h>
int main() {
int input;
while((input = getchar()) != EOF){
int escaped = 0;
if(input == '\t'){
putchar('\\');
putchar('t');
escaped = 1;
}
if(input == '\b'){
putchar('\\');
putchar('b');
escaped = 1;
}
if(input == '\\'){
putchar('\\');
putchar('\\');
escaped = 1;
}
if(escaped == 0){
putchar(input);
}
}
}
There are many ways to implement this and paxdiablo gave a couple of good ones. Here's one that illustrates the DRY principle via functional decomposition:
void putesc(char c)
{
putchar('\\');
putchar(c);
}
void ioloop(void)
{
for (int c;;)
switch (c = getchar())
{
case EOF: return;
case '\t': putesc('t'); break;
case '\b': putesc('b'); break;
case '\\': putesc(c); break;
default: putchar(c); break;
}
}
Adding another solution! It's handy for us newbies to enrich us, seeing variety of solutions.
#include <stdio.h>
/* a program to copy its input to its output, replacing tab by \t,
backspace by \b, backslash by \\ */
/* need double backslash to output a single backslash */
int main(){
int c; /* to store next character from getchar() */
while((c = getchar()) != EOF){
if( c != '\t' && c != '\b' && c != '\\') /* print all characters except special one's */
putchar(c);
else{
if(c == '\t'){ /* replacing tab by \t */
putchar('\\');
putchar('t');
}
if(c == '\b'){ /* replace backspace by \b */
putchar('\\');
putchar('b');
}
if(c == '\\'){ /* replace backslash by \\ */
putchar('\\');
putchar('\\');
}
}
}
}
I'm a rookie. But considering only what they taught until to that point, I came up with this answer.
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
if (c == '\t') {
putchar('\\');
putchar('t');
}
else if (c == '\b') {
putchar('\\');
putchar('b');
}
else if (c == '\\') {
putchar('\\');
putchar('\\');
}
else {
putchar(c);
}
c = getchar();
}
}
You are very close. Simply change the second "putchar()" in each block into an assignment statement and you have the correct output.
int c;
while((c=getchar())!=EOF)
{
if(c=='\t')
{
putchar('\\');
c = 't';
}
if(c=='\\')
{
putchar('\\');
c = '\\';
}
putchar(c);
}
#include <stdio.h>
int main(int argc, const char * argv[]) {
int c;
int tab = 't';
int backspace = 'b';
int backslash = '\\';
while((c = getchar()) != EOF){
if (c == '\t'){
putchar('\\');
putchar(tab);
}
else if(c == '\b'){
putchar('\\');
putchar(backspace);
}
else if(c == '\\'){
putchar('\\');
putchar(backslash);
}
else{ // All other characters EXCLUDING "tab, backspace and backslash"
// will always be printed.
putchar(c);
}
}
return 0;
}
Just before the exercise, the book mentions ASCII code and not more advanced statements. In consequence, I think the solution was oriented to use ASCII.
int c;
while ( (c = getchar()) != EOF ){
//92 is the ASCII code for the backslash \
if ( c == '\t'){
putchar(92);
putchar('t');
}else if ( c == '\\' ) {
putchar(92);
putchar(92);
}else if ( c == '\b' ) {
putchar(92);
putchar('b');
}else{
putchar(c);
}
}

K&R Exercise 1-9 (C)

"Write a program to copy its input to
its output, replacing each string of
one or more blanks by a single blank."
I'm assuming by this he means input something like...
We(blank)(blank)(blank)go(blank)to(blank)(blank)(blank)the(blank)mall!
... and output it like:
We(blank)go(blank)to(blank)the(blank)mall!
This is probably easier than I'm making it out to be, but still, I can't seem to figure it out. I don't really want the code... more so pseudo code.
Also, how should I be looking at this? I'm pretty sure whatever program I write is going to need at least one variable, a while loop, a couple if statements, and will use both the getchar() and putchar() functions... but besides that I'm at a loss. I don't really have a programmers train of thought yet, so if you could give me some advice as to how I should be looking at "problems" in general that'd be awesome.
(And please don't bring up else, I haven't got that far in the book so right now that's out of my scope.)
Look at your program as a machine that moves between different states as it iterates over the input.
It reads the input one character at a time. If it sees anything other than a blank, it just prints the character it sees. If it sees a blank, it shifts to a different state. In that state, it prints one blank, and then doesn't print blanks if it sees them. Then, it continues reading the input, but ignores all blanks it sees--until it hits a character that isn't a blank, at which point it shifts back to the first state.
(This concept is called a finite state machine, by the way, and a lot of theoretical computer science work has gone into what they can and can't do. Wikipedia can tell you more, though in perhaps more complicated detail than you're looking for. ;))
Pseudo code
while c = getchar:
if c is blank:
c = getchar until c is not blank
print blank
print c
C
You can substitute use of isblank here if you desire. It is unspecified what characters contrive blank, or what blank value is to be printed in place of others.
After many points made by Matthew in the comments below, this version, and the one containing isblank are the same.
int c;
while ((c = getchar()) != EOF) {
if (c == ' ') {
while ((c = getchar()) == ' ');
putchar(' ');
if (c == EOF) break;
}
putchar(c);
}
Since relational operators in C produce integer values 1 or 0 (as explained earlier in the book), the logical expression "current character non-blank or previous character non-blank" can be simulated with integer arithmetic resulting in a shorter (if somewhat cryptic) code:
int c, p = EOF;
while ((c = getchar()) != EOF) {
if ((c != ' ') + (p != ' ') > 0) putchar(c);
p = c;
}
Variable p is initialized with EOF so that it has a valid non-blank value during the very first comparison.
This is what I got:
while ch = getchar()
if ch != ' '
putchar(ch)
if ch == ' '
if last_seen_ch != ch
putchar(ch)
last_seen_ch = ch
Same explanation with Matt Joiner's, but this code does not use break.
int c;
while ((c = getchar()) != EOF)
{
if (c == ' ') /* find a blank */
{
putchar(' '); /* print the first blank */
while ((c = getchar()) == ' ') /* look for succeeding blanks then… */
; /* do nothing */
}
if (c != EOF) /* We might get an EOF from the inner while-loop above */
putchar(c);
}
I worked really hard at finding a solution that used only the material that has already been covered in the first part of the first chapter of the book. Here is my result:
#include <stdio.h>
/* Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. */
main()
{
int c;
while ((c = getchar()) != EOF){
if (c == ' '){
putchar(c);
while ((c = getchar()) == ' ')
;
}
if(c != ' ')
putchar(c);
}
}
Here is how I think of the algorithm of this exercise, in pseudo-code:
define ch and bl (where bl is initially defined to be 0)
while ch is = to getchar() which is not = to end of file
do the following:
if ch is = to blank and bl is = 0
--> output ch and assign the value 1 to bl
else --> if ch is = to blank and bl is = 1
--> do nothing
else --> output ch and assign the value 0 to bl
Example implementation in C:
#include <stdio.h>
#include <stdlib.h>
main() {
long ch,bl=0;
while ((ch=getchar()) != EOF)
{
if (ch == ' ' && bl == 0)
{
putchar(ch);
bl=1;
} else if (ch == ' ' && bl == 1) {
// no-op
} else {
putchar(ch);
bl=0;
}
}
return 0;
}
I wrote this and seems to be working.
# include <stdio.h>
int main ()
{
int c,lastc;
lastc=0;
while ((c=getchar()) != EOF)
if (((c==' ')+ (lastc==' '))<2)
putchar(c), lastc=c;
}
#include <stdio.h>
int main()
{
int c;
while( (c = getchar( )) != EOF )
{
if (c == ' ')
{
while ((c = getchar()) == ' ');
putchar(' ');
putchar(c);
}
else
putchar(c);
}
return 0;
}
#include <stdio.h>
main()
{
int c, numBlank=0 ;
while((c= getchar())!=EOF)
{
if(c ==' ')
{
numBlank ++;
if(numBlank <2)
{
printf("character is:%c\n",c);
}
}
else
{
printf("character is:%c\n",c);
numBlank =0;
}
}
}
First declare two variables character and last_character as integers.when you have not reach the end of the file( while(character=getchar() != EOF ) do this;
1. If character != ' ' then
print character
last_character = character
2. If character == ' '
if last_character ==' '
last character = character
else print character
Using the constraints of not using else or and operators. This code only prints a blank when the blank variable is equal to 1 and the only way to reset the counter is by typing something other than a blank. Hope this helps:
include
/* Write a program that replaces strings of blanks with a single blank */
void main(){
int c, bl;
bl = 0;
while((c = getchar()) != EOF){
if(c == ' '){
++bl;
if(bl == 1){
putchar(' ');
}
}
if(c != ' '){
putchar(c);
bl = 0;
}
}
}
Many others have already used the last character logic in their code, but perhaps the following version is easier to read:
int c, prevchar;
while ((c = getchar()) != EOF) {
if (!(c == ' ' && prevchar == ' ')) {
putchar(c);
prevchar = c;
}
}
#include <stdio.h>
main() {
int input, last = EOF;
while ((input = getchar()) != EOF) {
if (input == ' ' && last == ' ') continue;
last = input;
putchar(input);
}
}
I am at the same point in the book. and my solution goes with making a count++ if blank is found and making the count back to zero if anything other than blank is found.
For if statement I put another another check to check value of count (if zero) and then print.
Though at this point of learning I shouldn't be concern about efficiency of two methods but which one is efficient a.) Accepted solution here with while inside while or b.) the one I suggested above.
My code goes like below:
#include <stdio.h>
main()
{
int count=0,c;
for( ; (c=getchar())!=EOF; )
{
if(c==' ')
{
if(count==0)
{
putchar(c);
count++;
}
}
if(c!=' ')
{
putchar(c);
count=0;
}
}
}
#include <stdio.h>
main()
{
int CurrentChar, LastChar;
LastChar = '1';
while ((CurrentChar = getchar()) != EOF)
{
if (CurrentChar != ' ')
{
putchar(CurrentChar);
LastChar = '1';
}
else
{
if (LastChar != ' ')
{
putchar(CurrentChar);
LastChar = ' ';
}
}
}
}
a way to make it easier for the new people are stuck on this book
(by not knowing any thing then what brought up until page 22 in K&R).
credits to #Michael , #Mat and #Matthew to help me to understand
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) /* state of "an input is not EOF" (1) */
{
if (c == ' ') /* "blank has found" -> change the rule now */
{
while ((c = getchar ()) == ' '); /* as long you see blanks just print for it a blank until rule is broken (2) */
putchar(' ');
}
putchar(c); /* either state (2) was broken or in state (1) no blanks has been found */
}
}
1.Count the number of blanks.
2.Replace the counted number of blanks by a single one.
3.Print the characters one by one.
<code>
main()
{
int c, count;
count = 0;
while ((c = getchar()) != EOF)
{
if (c == ' ')
{
count++;
if (count > 1)
{
putchar ('\b');
putchar (' ');
}
else putchar (' ');
}
else
{
putchar (c);
count = 0;
}
}
return;
}
</code>
#include <stdio.h>
int main(void)
{
long c;
long nb = 0;
while((c = getchar()) != EOF) {
if(c == ' ' || c == '\t') {
++nb;
} else {
if(nb > 0) {
putchar(' ');
nb = 0;
}
putchar(c);
}
}
return 0;
}
To do this using only while loops and if statements, the trick is to add a variable which remembers the previous character.
Loop, reading one character at a time, until EOF:
If the current character IS NOT a space:
Output current character
If the current character IS a space:
If the previous character WAS NOT a space:
Output a space
Set previous character to current character
In C code:
#include <stdio.h>
main()
{
int c, p;
p = EOF;
while ((c = getchar()) != EOF) {
if (c != ' ')
putchar(c);
if (c == ' ')
if (p != ' ')
putchar(' ');
p = c;
}
}
I am also starting out with the K&R textbook, and I came up with a solution that uses only the material which had been covered up until that point.
How it works:
First, set some counter 'blanks' to zero. This is used for counting blanks.
If a blank is found, increase the counter 'blanks' by one.
If a blank is not found, then first do a sub-test: is the counter 'blanks' equal or bigger than 1? If yes, then first, print a blank and after that, set the counter 'blanks' back to zero.
After this subtest is done, go back and putchar whatever character was not found to be a blank.
The idea is, before putcharing a non-blank character, first do a test to see, if some blank(s) were counted before. If there were blanks before, print a single blank first and then reset the counter of blanks. That way, the counter is zero again for the next round of blank(s). If the first character on the line is not a blank, the counter couldn't have increased, hence no blank is printed.
One warning, I haven't gone very far into the book, so I'm not familiar with the syntax yet, so it's possible that the {} braces might be written in different places, but my example is working fine.
#include <stdio.h>
/* Copy input to output, replacing each string of one or more blanks by a single blank. */
main()
{
int c, blanks;
blanks = 0;
while ((c = getchar()) != EOF) {
if (c != ' ') {
if (blanks >= 1)
printf(" ");
blanks = 0;
putchar(c); }
if (c == ' ')
++blanks;
}
}
Like many other people, I am studying this book as well and found this question very interesting.
I have come up with a piece of code that only uses what has been explained before the exercice (as I am not consulting any other resource but just playing with the code).
There is a while loop to parse the text and one if to compare the current character to the previous one.
Are there any edge cases where this code would not work ?
#include <stdio.h>
main() {
// c current character
// pc previous character
int c, pc;
while ((c = getchar()) != EOF) {
// A truthy evaluation implies 1
// (learned from chapter 1, exercice 6)
// Avoid writing a space when
// - the previous character is a space (+1)
// AND
// - the current character is a space (+1)
// All the other combinations return an int < 2
if ((pc == ' ') + (pc == c) < 2) {
putchar(c);
}
// update previous character
pc = c;
}
}
for(nb = 0; (c = getchar()) != EOF;)
{
if(c == ' ')
nb++;
if( nb == 0 || nb == 1 )
putchar(c);
if(c != ' ' && nb >1)
putchar(c);
if(c != ' ')
nb = 0;
}
Here is my answer, I am currently in the same spot you were years ago.
I used only the syntax taught until this point in the books and it reduces the multiple spaces into one space only as required.
#include<stdio.h>
int main(){
int c
int blanks = 0; // spaces counter
while ((c = getchar()) != EOF) {
if (c == ' ') { // if the character is a blank
while((c = getchar()) == ' ') { //check the next char and count blanks
blanks++;
// if(c == EOF){
// break;
// }
}
if (blanks >= 0) { // comparing to zero to accommodate the single space case,
// otherwise ut removed the single space between chars
putchar(' '); // print single space in all cases
}
}
putchar(c); //print the next char and repeat
}
return 0;
}
I removed the break part as it was not introduced yet in the book,hope this help new comers like me :)
This is a solution using only the techniques described so far in K&R's C. In addition to using a variable to achieve a finite state change for distinguishing the first blank space from successive blank spaces, I've also added a variable to count blank spaces along with a print statement to verify the total number. This helped me to wrap my head around getchar() and putchar() a little better - as well as the scope of the while loop within main().
// Exercise 1-9. Write a program to copy its input to its output, replacing
// each string of one or more blanks by a single blank.
#include <stdio.h>
int main(void)
{
int blank_state;
int c;
int blank_count;
printf("Replace one or more blanks with a single blank.\n");
printf("Use ctrl+d to insert an EOF after typing ENTER.\n\n");
blank_state = 0;
blank_count = 0;
while ( (c = getchar()) != EOF )
{
if (c == ' ')
{
++blank_count;
if (blank_state == 0)
{
blank_state = 1;
putchar(c);
}
}
if (c != ' ')
{
blank_state = 0;
putchar(c);
}
}
printf("Total number of blanks: %d\n", blank_count);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int c, flag=0;
while((c=getchar()) != EOF){
if(c == ' '){
if(flag == 0){
flag=1;
putchar(c);
}
}else{
flag=0;
putchar(c);
}
}
return 0;
}
I hope this will help.
/*a program that copies its input to its output, replacing each string of one or more blanks by a single blank*/
#include <stdio.h>
#include<stdlib.h>
int main(void)
{
double c;
char blank = ' ';
while((c = getchar()) != EOF)
{
if(c == ' ')
{
putchar(c);
while(( c = getchar() )== ' ')
{
if(c != ' ')
break;
}
}
if(c == '\t')
{
putchar(blank);
while((c = getchar()) == '\t')
{
if(c != '\t')
break;
}
}
putchar(c);
}
return 0;
}
// K & R Exercise 1.9
// hoping to do this with as few lines as possible
int c = 0, lastchar = 0;
c = getchar();
while (c != EOF) {
if (lastchar != ' ' || c != ' ') putchar(c);
lastchar=c;
c=getchar();
}
Considering what's asked in the question, I have also made sure that the program runs smooth in case of various tabs, spaces as well as when they're clubbed together to form various combinations!
Here's my code,
int c, flag = 1;
printf("Enter the character!\n");
while ((c = getchar()) != EOF) {
if (c == ' '||c == '\t') {
c=getchar();
while(c == ' '|| c == '\t')
{
c = getchar();
}
putchar(' ');
if (c == EOF) break;
}
putchar(c);
}
Feel free to run all test cases using various combinations of spaces and tabs.
Solution1: as per topics covered in the k&R book:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
if (c == ' ')
{while ( getchar() == ' ' )
; // ... we take no action
}
putchar(c);
}
return 0;
}
Solution2 : using program states:
int main()
{
int c, nblanks = 0 ;
while ((c = getchar()) != EOF)
{
if (c != ' ')
{ putchar(c);
nblanks = 0;}
else if (c==' ' && nblanks == 0) // change of state
{putchar(c);
nblanks++;}
}
return 0;
}
Solution3 : based on last seen char
int main()
{
int c, lastc = 0;
while ((c = getchar()) != EOF)
{
if ( c != ' ')
{putchar(c);}
if (c == ' ')
{
if (c==lastc)
;
else putchar(c);
}
lastc = c;
}
return 0;
}

Resources