Print the input one word per line - c

right now I am writing a program on C language based on the task 1.12 from Brian and Ritchie book. The program has to output the input stream one word per line. Here is the code:
#include <stdio.h>
int main(){
int ct;
while((ct = getchar()) != EOF){
if(ct == ' '){
ct = ct - ' ';
putchar(ct);
printf("\n");
}else if(ct == '\n'){
ct = ct - '\n';
putchar(ct);
printf("\n");
}
}
}
It seems to work, but it only outputs blank lines when I enter the input. Where did I mess up?

In your code, you have the two cases where you check if ct is either a space (' ') or a newline character ('\n'), and these are the only places where you are printing out the character, using putchar. Your code isn't ever printing anything out outside of these two cases, so you need to add a case to handle regular characters and to print those out as well. Something like:
#include <stdio.h>
int main(){
int ct;
while((ct = getchar()) != EOF){
if(ct == ' '){
ct = ct - ' ';
putchar(ct);
printf("\n");
}else if(ct == '\n'){
ct = ct - '\n';
putchar(ct);
printf("\n");
} else {
putchar(ct)
}
}
Also, while putchar does take an int as an argument, you do not need to manually convert it using ct - ' ', for example. You can pass the ct char directly to putchar and it will print it out accordingly

Related

Counting words program in C omitting double spaces and punctuation

I am doing a course on the basics of C programming, I've been given a task to create a program that counts the number of words in a sentence, I've achieved this, however I have a secondary task to stop the program from counting punctuation, on top of this if i type in a consecutive space i need the program to ignore it, i don't know how to get round it. could anyone point me into the right direction, I am not looking for anyone to write the code for me.
here is my code:
#include <stdio.h>
int main()
{
const char end = '.';
int words = 1;
printf("please enter a sentence: \n");
char c = getchar();
while (c != end)
{
c = getchar();
if (c == ' ')
words++;
}
printf("the total number of words is %d", words);
getchar();
getchar();
}
Working from the code you give (i.e. counting words by finding delimiting spaces), you can solve the multiple spaces problem by remembering the last character ignoring subsequent spaces
while (c != end)
{
c = getchar();
if (c == ' ' && previous_c != ' ')
words++;
previous_c = c;
}
Note though that if the user begins the input with a single space, then the program will still count this as one word. To prevent this you should initialse previous_c to some known value (e.g. 0) and check for this case also. This means the if condition would become (c == ' ' && (previous_c != ' ' || previous_c == 0))
As Cool Guy commented, the program you've shown already ignores punctuation as-is.
As another improvement I would suggest looking at using a do...while loop instead of the while loop to reduce the places you need to call getchar()
I would split it in 2 loops. One for skipping all non-word-chars and a second to skip the word-chars. Between these loops starts a word and will be counted.
#include <stdio.h>
int main()
{
char c;
int words = 0;
printf("please enter a sentence: \n");
for(;;) {
while((c=getchar())!=EOF && !isalpha(c));
if(c==EOF) break;
words++;
while((c=getchar())!=EOF && isalpha(c));
if(c==EOF) break;
}
}

K&R C Exercise 1-9 *almost* solved

K&R C Exercise 1-9 states:
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
I have nearly solved this exercise, but the code I've written (see below) always prints an extra space before the first nonspace character. So input that looks like this
X(space)(space)X(space)(space)X(space)(space)X
results in output that looks like this
(space)X(space)X(space)X(space)X
#include <stdio.h>
int main()
{
int c; //current input character
int s; //consecutive input space counter
c = getchar();
s = 0;
while ((c = getchar()) != EOF){
if (c == ' '){
++s;
if (s == 1) //uses the counter to print only the
putchar(' '); //first space in each string of spaces
}
else {
putchar(c);
if (s != 0) //resets the space counter when it
s = 0; //encounters a non-space input character
}
}
return 0;
}
Why does my code always print a leading space when I run it?
How can I modify this code to print the first input character first instead of a leading space?
Do not throw away the first char. #David Hoelzer
// Commented out
//c = getchar();
s = 0;
while ((c = getchar()) != EOF){
Also note unbalanced } near return 0;

K&R exercise 1-9. Putchar and getchar

I was doing the 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) of this book and it seems I'm not quite getting it. So far this is my code:
#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF)
if (c == ' ') {
while (c == ' ') {
c = getchar();
}
putchar(' ');
} else {
putchar(c);
}
return 0;
}
It's wrong since the sentence hey(blank)(blank)(blank)now comes as hey ow. Always the first letter after de last blank is erased. I think it is a pretty silly bug but I can't see how to fix it. I'll appreciate any piece of advice.
PS: sorry for my English and if you don't understand something, please tell me.
In this if statement (I have formatted it that it could be readable)
if (c == ' ')
{
while (c == ' ')
{
c = getchar();
}
putchar(' ');
}
you are skipping the non-blank character that just has been read because in the outer loop
while ((c = getchar()) != EOF)
you are reading the next character.
The program can be written for example the following way
#include <stdio.h>
int main( void )
{
int blank = 0;
int c;
while ( ( c = getchar() ) != EOF )
{
if ( !blank || c != ' ' ) putchar( c );
blank = c == ' ';
}
return 0;
}
Take into account that according to the C Standard main without parameters shall be declared like
int main( void )
Because the while (c == ' ') is reading until it finds a non-space. So, it stops when you reach the 'n', but you are not putting that character. After the putchar(' '), add a putchar(c); to print the character after the string of blanks.
Because in the inner while you are getting the 'n' and then, in the outer while condition, you are getting another character, that is 'o'.

K&R Exercise 1-20 The Programming Language 2nd edition

What should i do in this program. I cant understand.
The question is as : Write a program detab that replaces tabs in the input with the proper number
of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns.
Should n be a variable or a symbolic parameter?
I started by replacing the tabs ('\t') with space (' ').
But i guess this is the wrong approach.
please suggest ?
and btw what should n be? variable or symbolic parameter?
code so far:
#include<stdio.h>
#define TAB 5
int main() {
int i, c;
while((c = getchar()) != EOF) {
if(c == '\t') {
for(i = 0; i < TAB; ++i)
putchar(' ');
} else
putchar(c);
}
return 0;
}
In all the questions posted for this exercise i couldn't understand the meaning.
This is my final code, please tell me if it has any problems / bugs. I think it is working as it should..
thanks to #Nit, #Chrono Kitsune , #dasblinkenlight and all the others who helped.
#include<stdio.h>
#define TAB 8
int main() {
int c, count = 0, space = 0;
while((c = getchar()) != EOF) {
if(c == '\t') {
space = (TAB - (count % TAB));
while(space > 0){
putchar(' ');
count++;
space--;
}
}
else{
putchar(c);
++count;
}
if(c == '\n')
count = 0;
}
return 0;
}
What you are doing is not what the exercise wants you to do: rather than inserting a fixed number of spaces for each tab, you should be inserting a different number of spaces depending on how much has been printed on the line so far.
It does not matter how you take the number of spaces per tab - the way you made it a preprocessor constant is perfectly fine. However, rather than producing TAB spaces regardless of where the '\t' has been found, you program needs to count how much "regular" characters have been printed, and count how many spaces are needed when it sees '\t'.
Make a variable count for characters printed so far. Initialize it to zero, and then reset it back to zero each time you see a '\n' character. When you call putchar, also make count++.
Now when you see a tab '\t' compute how far you are form the next tab stop. The expression for that is
TAB - (count % TAB)
That is how many spaces you need to print.
This should be enough information for you to go back and fix your program - I think you need to write only five additional lines of code (not counting lines for curly braces that you would need to insert) in order to finish this exercise.
The first step is to understand the problem. As I read it over and over for several times at first I couldn't understand what exactly it wants me to do. It's because some concepts weren't clear or familiar to me before I searched for more information about tab. First, what is a tab and what is a tab stop exactly? A tab is a character represented by the escape sequence \t in many contexts. Just like other characters such as letters or digits, it's a character, but with special usage, so it's not a wide space or 4 or 8 spaces as it appears to be. Being displayed like a wide space or 4 or 8 spaces is just what it's designed for, which aligns each tab-delimited group of texts on multiple lines to make the region look like a table, but underneath on the level the software sees it's just a character. Tab stops are positions on the line where the cursor goes when the Tab key is pressed. These positions are fixed on the line according to the width or number of characters (or columns, all referring to the same concept) with which the Tab character is displayed. For example, on Windows Notepad the default width for Tab is 8 characters, and when you type Tab key the cursor would move behind the 8th, 16th, 24th... character. You can type 0s on the first line to see the effect more clearly:
00000000000000000000000000000000
Ivan Hello World
This is a table
delimited by tab
Now reading the problem over again it's clear to me that it's about replacing the Tab characters with spaces while maintaining the original table look. Then you can start writing your code to calculate how many spaces are needed for each Tab. Here's my complete code for this exercise:
#include <stdio.h>
#define MAX_LENGTH 1000
#define LINE_NUM 100
#define TAB_WIDTH 8
int readLine(char line[], int maxLength);
void copy(char from[], char to[]);
void detab(char line[], char result[]);
main() {
printf("Input: \n");
char lines[LINE_NUM][MAX_LENGTH];
char line[MAX_LENGTH];
char result[MAX_LENGTH];
int lineId = 0, length = 0;
while ((length = readLine(line, MAX_LENGTH)) != 0) {
detab(line, result);
copy(result, lines[lineId]);
lineId++;
}
printf("Output: \n");
for (int i = 0; i <= lineId; i++) {
printf("%s\n", lines[i]);
}
}
int readLine(char line[], int maxLength) {
char ch;
int length = 0;
while ((ch = getchar()) != EOF && ch != '\n' && length < maxLength) {
line[length] = ch;
length++;
}
if (ch == '\n') {
line[length] = '\0';
}
return length;
}
void copy(char from[], char to[]) {
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
i++;
}
to[i] = '\0';
}
void detab(char line[], char result[]) {
int i = 0;
char ch;
int column = 0;
int spaces;
int nextTabStop;
while ((ch = line[i++]) != '\0') {
if (ch == '\t') {
spaces = TAB_WIDTH - column % TAB_WIDTH;
nextTabStop = column + spaces;
for (; column < nextTabStop; column++) {
result[column] = ' ';
}
} else {
result[column] = ch;
column++;
}
}
result[column] = '\0';
}
First, try to get familiar with '\t' (TAB character) and see what happens when you print
'\t' + ','
'.' + '\t' + ','
'..' + '\t' + ','
And so on. You will see that there is a fixed number of initial '.'s in which the ',' character after '\t' is on the same position, this means that the '\t' length is not fixed, so if you try to replace it with a fixed number of ' ' characters (white spaces), the output will be different from the input.
Understanding that, your task is to create a program that replaces all '\t' characters with white spaces, so you have to calculate the number of necessary white spaces to print for each '\t' char you read. This is what I've done so far.
#include <stdio.h>
#define WSPT 8 // white spaces per tab
main () {
int c, counter;
counter = 0; // distance from the previous tab stop
while((c = getchar()) != EOF) {
if(c == '\t') {
for(int i = 0; i < WSPT - counter; ++i)
putchar(' '); // print white spaces until reach the next tab stop
counter = 0; // you are again at the start of a tab stop
} else {
putchar(c);
if(c != '\n')
counter = (counter + 1) % WSPT; // move 1 step
else
counter = 0; // you are again at the start of a tab stop
}
}
}
Okay, his is actually a very simple question and I'm not sure why everyone is making it more complicated than it is. We need to simply replace tab's with the necessary number of blanks so the resulting output looks no different than if there was a tab there.
No need for a million lines of code... a few will do...
#include <stdio.h>
/* A program *detab* that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assuming a fixed set of tabstops, say every n columns */
#define TAB_WIDTH 4 // tab width on particular machine
int main()
{
int c;
int i = 0;
while((c = getchar()) != EOF) {
if(c != '\t')
putchar(c);
else
while(i < TAB_WIDTH - 1){
putchar(' ');
i++;
}
}
}
why so complicated stuffs..just do this
#include <stdio.h>
int main()
{
int c, tab=6, count=0;
while((c=getchar())!=EOF)
{
count++;
if (c=='\t')
{
for (int i=count; i%(tab+1)!=0; i++) putchar(' ');
}
else putchar(c);
if(c=='\n') count=0;
}
}

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