Text stream K&R exercises


 
Thread Tools Search this Thread
Operating Systems OS X (Apple) Text stream K&R exercises
# 1  
Old 01-14-2010
Text stream K&R exercises

Hello, ladies, gentlemen.

First I suppose I should introduce myself.

I've been poking at C since a long time ago, somewhere around 1990. (Don't misinterpret that. "Poking at C", in this statement, means that I jumped on it, studied it for anything from a day to a weekend to a finished "Hello, World" program, then forgot about it while years of life roared by. The statement is not meant to imply that I have years and years and years of programming, rather, it simply means that lots and lots of time went by while my programming skills stood still.) I'm not a professional, I'm not a student, and I don't really know that much about it, other than this: it fascinates me.

My knowledge of C and programming comes from these disjointed forays, books, the 'net, and the occasional burst of help from friends who are REAL programmers.

The difference between us is profound. Given a project, they sit down and methodically start laying out a process to complete the solution, while I sit down and start eliminating ways that don't work. Their way is faster.

I program on a Mac, currently with OS X, (10.6.2, Snow Leopard). I use Xcode as my environment, and I compile C with Terminal and everything else with Xcode.

When I started, the Big Thing was CodeWarrior, and I never learned to hammer out code on a Unix platform. In fact, because the Mac environment was so different then, I never learned to do a lot of basic stuff.

Of course, back in the day, I bought a copy of K&R's The C Programming Language, and I've benefitted from it immensely.

I've always looked at the exercises, and promised myself that someday, I would come back and see to them.

That day has arrived.

I just (two nights ago, in fact) figured out how to use Xcode to write C files, and how to use the cc command in Terminal to compile them. After a big search, I figured out that "./a.out" runs the output, and I became able, for the first time, to write, compile and run programs that are suitable (in my unlearned opinion) for the K&R exercises.

I know that programming has advanced, and I know that Computer Years are even more extreme than Dog Years; I know that Objective C is what Xcode is all about now, and I remember pulling my hair out while I tried to write code to get a window to scroll, a task that Interface Builder handles auto-magically now.

Still, I've always felt that if I understood ANSI C better, my understanding of programming in general would be better, so I've decided to work my way through the K&R book, and hunt down the answers to every stupid little exercise.

So.

I managed to make it through the first five exercises, and I have code that should solve 1-6, and I solved 1-7.

However. (You knew that was coming, didn't you?)

The exercises that center on getchar and putchar puzzle me: I don't see where they are getting the text stream, and I believe that it is coming from the keyboard.

That creates a couple problems, first is that I don't know what to type to generate an EOF character, so my programs (and one of their programs) are endless loops, and you have to close the Terminal window to get them to quit.

This code is also a problem:

Code:
// Test.c

#include <stdio.h>

	//Verify that the expression "getchar() != EOF" is 0 or 1.
	//Exercise 1-6 on page 17.

main()	{
	
	int	c;
	
	c = getchar();
	
	while (c != EOF) {
		while (c != 1) { 
			while (c != 0) {// You only get here if c is not 1.
				printf("EOF is not 1 or 0.");	//c is not 1 or zero.
			}	//end while test for zero
		}	// end while test for 1
		
		printf("\nThe value passed, because EOF is ");
		printf("%d\n",	c);
	}
}

When I run it, it doesn't appear to do anything, until I type something. Then it enters an endless loop, and doesn't exit unless I close the Terminal window.

I don't see how I'm creating a loop.

I also don't see (in the K&R book) how to obtain a text stream other than from the keyboard.

Any help will be welcome.

This code is a different type of problem:

Code:
// count.c
#include	<stdio.h>

// count characters in input, page 18 of C book, version 1

main()	{
	
	long	nc;
	
	nc = 0;
	
	while (getchar()!=EOF) {
		++nc;
		printf("%ld\n",	nc);
	}	// end of while
}	// end of main

This code is straight out of the K&R book. What it does is nothing, until you type something. Then it generates a random number of numbers. It also doesn't quit unless you quit the Terminal window.

I appreciate your looking. Thank you.
# 2  
Old 01-14-2010
Hi.
the code is correct . Which Operating System do you use?
If you are on GNU/Linux then EOF is 'ctrl+D'
If you are on Windows(eww) then EOF is 'ctrl+Z' ( I guess )

when you press ctrl+D then the program will err experience 'end of file' character and it will come out of loop.

Regards,
Enjoy.
# 3  
Old 01-14-2010
Quote:
Originally Posted by Jammer Six
Code:
// Test.c

#include <stdio.h>

	//Verify that the expression "getchar() != EOF" is 0 or 1.
	//Exercise 1-6 on page 17.

main()	{
	
	int	c;
	
	c = getchar();
	
	while (c != EOF) {
		while (c != 1) { 
			while (c != 0) {// You only get here if c is not 1.
				printf("EOF is not 1 or 0.");	//c is not 1 or zero.
			}	//end while test for zero
		}	// end while test for 1
		
		printf("\nThe value passed, because EOF is ");
		printf("%d\n",	c);
	}
}

When I run it, it doesn't appear to do anything, until I type something. Then it enters an endless loop, and doesn't exit unless I close the Terminal window.

I don't see how I'm creating a loop.
You've got 3 while-loops in there, each one checking the value of the variable c, which is never changing. So as soon as you enter any character, enters the outermost while loop. Since it's pretty unlikely to enter the characters with the ASCII codes 0 or 1 via the keyboard, the two inner loops will run until killed (by Ctrl+C or by closing the Terminal).
Quote:
Originally Posted by Jammer Six
I also don't see (in the K&R book) how to obtain a text stream other than from the keyboard.

Any help will be welcome.
There are 2 possibilities: you can do a redirection in your terminal (eg
Code:
cat /some/file | ./a.out

), or by opening a file using open/fopen. If I remember correctly, those are introduced later in the book.
Quote:
Originally Posted by Jammer Six
This code is a different type of problem:

Code:
// count.c
#include	<stdio.h>

// count characters in input, page 18 of C book, version 1

main()	{
	
	long	nc;
	
	nc = 0;
	
	while (getchar()!=EOF) {
		++nc;
		printf("%ld\n",	nc);
	}	// end of while
}	// end of main

This code is straight out of the K&R book. What it does is nothing, until you type something. Then it generates a random number of numbers. It also doesn't quit unless you quit the Terminal window.
getchar() is a so-called blocking function. That means, it will sit and block the calling program until it can return something, in this case a character read from stdin. While it gets characters that don't signal an End-Of-File, it will count up.

EOF is usually input by the keyboard combination Ctrl+D on Unix-like systems (including BSD-descended MacOS X)
# 4  
Old 01-14-2010
Thanks to both of you.

I see the problem with the while loops.

I'll try the control-D combination, then I'll gnash my teeth and pull my hair for awhile on another way to test input.
# 5  
Old 01-14-2010
Four hints:
  • General: C doesn't know boolean values, it just uses 0 as false, and 1 as true.
  • General: any comparison can be used as a right-hand value, like a function
  • In exercise 1-6: use if to compare
  • In exercise 1-7: almost there, just move the printf() so it's called only once, when everything else is done, to avoid cluttering the screen
# 6  
Old 01-15-2010
Okay, I'm back. Smilie

I've been examining if.

For 1-6, I wrote this, thinking that perhaps I was just making it too complicated:

Code:
/*
 *  verify.c
 *  
 *	Exercise 1-6, Verify that the expression "getchar() != EOF is 0 or 1.
 */

#include <stdio.h>

main(){
	
	int v;
	
	while (v=(getchar() != EOF)) { // get another character, make the test
		
		printf("%d\n",v);	// prints as long as it isn't EOF
	}	// end of while
	
	printf("Reached EOF, program ends.\n\n");
	
}	// end of main

When I run it, I see a strange problem.

It produces a list of 1s, (because the statement is always true, if there's another character that isn't EOF) and then when you hit Control-D (Thank you, thank you!) it prints the end statement.

The problem is that it always prints one extra 1!

That is, if I type a string of five letters into the keyboard, it will print six ones.

I don't see where the extra one is coming from, the only way to reach the printf statement is for there to be a character in the character stream. I think. Maybe. Perhaps. Probably. In my fantasy world.

So where is the extra 1 coming from?

P.S. Now I'm off to nail 1-8, which looks easy.

---------- Post updated at 20:43 ---------- Previous update was at 20:32 ----------

Quote:
Originally Posted by gaurav1086
Which Operating System do you use?
Gaurav, thank you, I'm using Mac OX X, 10.6.2, called Snow Leopard, and Control-D does indeed work.

Thank you again. Smilie

Last edited by Jammer Six; 01-15-2010 at 12:39 AM.. Reason: P.S.
# 7  
Old 01-15-2010
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.
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