Text stream K&R exercises


 
Thread Tools Search this Thread
Operating Systems OS X (Apple) Text stream K&R exercises
# 8  
Old 01-15-2010
Quote:
Originally Posted by pludi
You said that it prints 6 1s if you just enter 5. Do you hit Return after entering the 5 characters? If so, there's your sixth.
Oh! The return character! Of course! duh...

Now, of course, I have another problem. I thought 1-8 would be easy, but not so much.

The code:

Code:
/*
 *  blank.c
 *	
 *	Exercise 1-8, write a program that counts blanks, tabs and newlines.
 */

#include <stdio.h>


main(){
	int x,s,t,n;
	
	s = 0; // counter for spaces
	t = 0; // counter for tabs
	n = 0; // counter for newlines
	
	while (x = getchar()!=EOF){
		
		if (x = " ") // x is a blank space
			s++;
		if (x = "\t") // x is a tab
			t++;
		if (x = "\n") // x is a newline
			n++;
		
	} // End while

	printf("\nThere were ");
	printf("%d", s);
	printf(" spaces.\n");
	
	printf("There were ");
	printf("%d", t);
	printf(" tabs.\n");
	
	printf("There were ");
	printf("%d", n);
	printf(" newlines.\n\n");
	
} // End main

It stays in a loop, but the loop isn't very well behaved.

It takes the input, and I figured that it should only increment the various counters if the character in question were the right type-- but no.

It increments EACH counter with EVERY character.

It has no discrimination. Enter 6 characters and a return, and it will say that there are 7 spaces, 7 tabs and 7 newlines.

I don't see how it's getting into each if statement! It's breaking all the rules!
# 9  
Old 01-15-2010
Don't worry, it's a typical beginners error.
  • = is an assignment. As long as the lvalue isn't a constant, it always returns a true value.
  • == is an comparison.
# 10  
Old 01-16-2010
Oh, for goodness sake.

I see it.

{sigh...}

So, it's not comparing anything in my code, it's assigning the values of space, tab and newline to the variable x, which is always successful, and, therefore, always true. So every if loop executes on every character.

/*******************************/
Update.

I re-wrote the code, and made another rookie mistake that plagued me for two hours.

This code is the solution:

Code:
/*
 *  blank.c
 *	
 *	Exercise 1-8, write a program that counts blanks, tabs and newlines.
 */

#include <stdio.h>


main(){
	int x,s,t,n;
	
	s = 0; // counter for spaces
	t = 0; // counter for tabs
	n = 0; // counter for newlines
	
	while ((x = getchar()) != EOF){
		
		if (x == ' ') // x is a blank space
			s++;
		if (x == '\t') // x is a tab
			t++;
		if (x == '\n') // x is a newline
			n++;
		
	} // End while

	printf("\nThere were ");
	printf("%d", s);
	printf(" spaces.\n");
	
	printf("There were ");
	printf("%d", t);
	printf(" tabs.\n");
	
	printf("There were ");
	printf("%d", n);
	printf(" newlines.\n\n");
	
} // End main

However, in the comparisons, I initially used double quotes, and the program insisted that there were zero spaces, zero tabs, and zero newlines-- exactly what I'd initialized the variables to. They weren't incrementing.

I finally found the answer in K&R-- they had mentioned it, and I read right over it. It has to be single quotes, double quotes is a text string.

I won't say that an exercise looks easy again. Smilie I'm off to look at 1-9.

---------- Post updated 01-16-10 at 01:37 ---------- Previous update was 01-15-10 at 01:43 ----------

Okay, I'm back.

Now I'm completely baffled.

Exercise 1-9, with this code:

Code:
/*
 *  copy.c
 *  
 *	Exercise 1-9. Write a program to copy it's input to it's output,
 *	replacing each string of one or more blanks by a single blank.
 */


#include	<stdio.h>

main() {
	
	int	c;	//the current character
	
	while ((c = getchar()) != EOF) {
		
		if (c == ' ') { // If there's a blank space
			
			while ((c = getchar() == ' ')) { /* Get another character, check to 
											 see if it's a blank space. We don't
											 care how many blank spaces there are, so 
											 if it's a blank space, do nothing. If it's
											not a blank space, break out of the while
											 loop. */
				
				; /* The do nothing command. When it breaks out of this loop, 
				   c will be holding the first character after the string 
				   of blank spaces.*/
				
			} // end while
			
			printf(" "); //But there was at least one blank space, so we need
						 // to print one blank space.
		}  // end if
		
	printf(c); // print the character
				   
	}	// end while
}	// end main

When I run this code with a text file, using cat /Text.txt|./a.out

the only thing that happens is that another curser appears and says:

Bus error.

My other programs still run, this is the only one that creates a bus error.

---------- Post updated at 05:02 ---------- Previous update was at 01:37 ----------

Okay, I replaced the final printf with a putchar, and the bus error went away.

The program now runs, but it doesn't do anything like it should.

Code:
/*
 *  copy.c
 *  
 *	Exercise 1-9. Write a program to copy it's input to it's output,
 *	replacing each string of one or more blanks by a single blank.
 */


#include	<stdio.h>

main() {
	
	int	c;	//the current character
	
			while ((c = getchar()) != EOF) {
		
		if (c == ' ') { // If there's a blank space
			
			while ((c = getchar() == ' ')) { 
				
/* Get another character, check to see if it's a blank space. I don't
 care how many blank spaces there are, so if it's a blank space, do nothing. 
 If it's not a blank space, break out of the while loop. */
				
				; /* The do nothing command. When it breaks out of this loop, 
				   c will be holding the first character after the string 
				   of blank spaces.*/
				
			} // end while
			
			printf(" "); //But there was at least one blank space, so we need
						 // to print one blank space.
		}  // end if
		
	putchar(c); // print the character
				   
	}	// end while
}	// end main

Now it deletes "random" characters, (I'm sure there's a pattern, or at least a reason, but I don't see it.) and leaves long lines of blank spaces. The mystery continues.

Last edited by Jammer Six; 01-15-2010 at 09:04 AM.. Reason: update
# 11  
Old 01-16-2010
You can use a flag as "mnemonic", something like this:

Code:
#include <stdio.h>

main()
{
    int c, flag;

    while ((c = getchar()) != EOF){
        if (c == ' ') {
            if (!flag) {
                printf("%c", c);
                flag=1;
            }
            continue;
        }
        printf("%c", c);
        flag=0;
    }
}

Smilie
# 12  
Old 01-17-2010
Thank you, Franklin.

I took your suggestion of a flag, and after wrestling with it for a few hours, came up with this:

Code:
/*
 *  copy.c
 *  
 *	Exercise 1-9. Write a program to copy it's input to it's output,
 *	replacing each string of one or more blanks by a single blank.
 */


#include	<stdio.h>

main() {
	
	int	c;	// The current character
	int	blank;	// flag that is set when we get the first blank space
	
	c = blank = 0;
	
	printf("\n\n");	// just so I can read the output
	
	while ((c = getchar()) != EOF) {
		
		if (c != ' ')		{	// if c is not holding a blank space
			putchar(c);			// print it
		}						// end if
			else if (!blank) {	// c is a blank space, if it's the first blank space
				blank = 1;		// set blank to show we already have the first blank
				putchar(c);		// printed
			}					// end else if
		
			else	{			// we're in a string of two or more blanks
				
				while ((c = getchar()) == ' ') {
					
/* as long as we're in the string of blanks					
 do nothing, kick out when we get the first non-blank	*/
					
					;	// The do nothing command		
				}		// end while
				
/* c now holds the first character after the string of blanks, 
reset blank, print one blank, and print the character */
				
				blank = 0
				printf(" ");
				putchar(c);
				
			}					// end final else
	}							// end main while loop
	
	printf("\n\n");				// just so I can read the output
	
}								// end main

It works, and it works reliably, but there's one thing I don't like about it.

If I'm following it correctly, (and I'm pretty sure I am) the flag blank carries a 1 as soon as a single blank is encountered.

That is, if you ran it on this sentence, the space between "That" and "is" would set blank to one, and it would be one until it was re-set, and it wouldn't be re-set until the word "if".

So it would work, it wold do its assigned task correctly, and the code would use the first else if when it didn't have a blank set, and the second else if when it did.

So my only gripe is that the flag blank isn't reliable-- it does not show the truth about whether the first blank has been encountered at all times.

On the other hand, when I swore at it, I woke my wife up, so I think I'll put it away for tonight.
# 13  
Old 01-17-2010
Quote:
Originally Posted by Jammer Six
So my only gripe is that the flag blank isn't reliable-- it does not show the truth about whether the first blank has been encountered at all times.
Is that necessary? You can also use the flag as a counter and increase the value if you encounter a space:

Code:
blanc++;

# 14  
Old 01-18-2010
I started thinking about what you said, and I realized that it doesn't matter.

The goal is to replace strings of blanks with single blanks, and then I realized I was over-thinking it, and making it too complicated.

So I stripped out the counter, did away with all the unnecessary activity, and came up with this, which I believe is a better solution.

Thank you, Franklin, Smilie

Code:
/*
 *  copy2.c
 *  
 *	Exercise 1-9. Write a program to copy it's input to it's output,
 *	replacing each string of one or more blanks by a single blank.
 */

#include <stdio.h>

main(){
	
	int	c;	// the current character
	
	printf("\n\n");
	
	while ((c = getchar()) != EOF) { // while not EOF
		if (c == ' ') {
			
/* You enter this if loop if you hit one or more blank spaces.
No matter how many blank spaces there are, run through all of
 them, doing nothing. */
			
			while ((c = getchar()) == ' ') {
				; // do nothing.
			} // end while loop
			
/* c is now holding the first character afer however many blanks there were.
 Replace all the blanks by printing one blank to output, 
 then leave the if loop and print the character. */
			
			printf(" "); 
		}  // end if loop
		
		putchar(c);
		
	} // end while loop
	
	printf("\n\n");
} // end main

And now I believe I'll look at 1-10.

---------- Post updated at 13:49 ---------- Previous update was at 06:42 ----------

1-10 was a piece of cake, other than chasing my tail all over the book trying to print two backslashes...

I also don't get the idea of printing two backspaces.

If you backspace, you erase what you just typed, and there's nothing there-- so there's not ever anything to print!

Would there ever be a legitimate reason to record backspaces, and print them in output?

Seems like they would just make things complicated...

Code:
/*
 *  replace.c
 *  
 *	Exercise 1-10. 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 backslashes
 *	visible in an unambiguous way.
 */

#include	<stdio.h>

main(){
	int	c; // the character
	
	while ((c = getchar())!= EOF) {
		
		if (c == '\t') { // if it's a tab
			printf("\\t");
		} // end if
		
		else if (c == '\b') {	// backspace
			printf("\\b");
		}  // end else if
		
		else if (c == '\\') {	// backslash
			printf("\\\\");
		}  // end else if
		
		else 
			putchar(c);

	} // end while loop
} // end main

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Help with a question in one of my exercises

Hello, so I'm taking unix in one of my classes and I've been having fun, but I got stuck at this one question that I'm supposed to know how to answer but I can't wrap my head around it, I figured I'll post it here and see if someone can shed some light into what I'm doing wrong. Here's the... (1 Reply)
Discussion started by: hiwolf25
1 Replies

2. Shell Programming and Scripting

Insert Text after one, two, three lines & so on..

I want to insert "Text" in each file as a place where I mentioned below "Insert Text Here". These files are something like news of newspaper. Generally, newspaper headlines contain one or two lines. I don't know how it can be identified whether Text is inserted after first line or second line. ... (10 Replies)
Discussion started by: imranrasheedamu
10 Replies

3. Shell Programming and Scripting

Extract & Manipulate continous data stream-- tcpdump

Hello; I have this rather tricky problem to solve --(to me, anyways) .. I am processing the following one liner with tcpdump.. tcpdump -i T3501 -A ether host 00:1e:49:29:fc:c9 or ether host 00:1b:2b:86:ec:1b or ether host 00:21:1c:98:a4:08 and net 149.83.6.0/24 | grep --line-buffered -B... (5 Replies)
Discussion started by: delphys
5 Replies

4. Shell Programming and Scripting

Array & text file

Hi all, i have a text file such as: 10 17:54:47,213 10 17:54:47,214 10 17:54:49,338 10 17:54:49,399 10 17:54:50,402 10 17:54:50,403 11 17:54:47,213 11 17:54:47,213 11 17:54:49,362 11 17:54:49,422 11 17:54:50,429 11 17:54:50,429 11 17:54:50,429 11 17:54:50,429 11 17:54:51,510 12... (10 Replies)
Discussion started by: sbamap
10 Replies

5. Shell Programming and Scripting

I would like to have some exercises to develop my skills

Hi , I would like to do some exercises/scripts in order to develop my skills in shell scripts, can someone pass me some links/suggestions where i can find this? Thanks a lot :) (3 Replies)
Discussion started by: prpkrk
3 Replies

6. Shell Programming and Scripting

[Video stream] network stream recording with mplayer

Hi I used this command: mplayer http://host/axis-cgi/mjpg/video.cgi -user root -passwd root \ -cache 1024 -fps 25.0 -nosound -vc ffh264 \ -demuxer 3 -dumpstream -dumpfile output.avi It's ok but... Video Playing is very fast! Why? Is it a synch problem? What parameter I have to use for... (1 Reply)
Discussion started by: takeo.kikuta
1 Replies

7. Shell Programming and Scripting

Need ideas for practice exercises in sh

I did an assignment for sh scripting back in november, and I found it quite fun learning. I would like to retain this knowledge as I'm pretty sure it was my only scripting assignment, from now on in my programming course we won't be doing any scripting apart from the typical makefile scripts. The... (6 Replies)
Discussion started by: gcampton
6 Replies

8. Shell Programming and Scripting

regex to remove text before&&after comma chars

Hi, all: I have a question about "cleaning up" a huge file with regular expression(s) and sed: The init file goes like this: block1,blah-blah-blah-blah,numseries1,numseries2,numseries3,numseries4 block2,blah-blah-blah-blah-blah,numseries,numseries2,numseries3,numseries4 ...... (3 Replies)
Discussion started by: yomaya
3 Replies

9. Shell Programming and Scripting

Shall Scripts exercises

I have just 3 things that I really need to know the solution, please allow me to show it. any help would be nice script that backup a file. The file name to backup should be provided as input parameter, the backup file should have the same file name with the extension ".bak". If the user... (1 Reply)
Discussion started by: anything
1 Replies

10. UNIX for Dummies Questions & Answers

exercises in shell

Hi, I am a beginner at shell scripting, though I have several years of Oracle programming experience. Can anyone recommend a site where I can find some exercises on shell programming. Is there anywhere I can telnet as I dont have UNIX OS on my PC? Thanks Rohit (1 Reply)
Discussion started by: rohitv
1 Replies
Login or Register to Ask a Question