473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

K&R2 exercise question

Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:
/************************************************** ****************************
* K&R2 Exercise 1-9
* Write a program to copy its input to its output, replacing strings
of blanks
* with a single blank.
************************************************** ****************************/
#include <stdio.h>

int main(void) {

int c= 0, lastc= 0;

while((c= getchar()) != EOF) {

if (c == ' ') {
if (lastc != ' ') {//if c *is* a space and lastc is
putchar(c);//*not* a space, print the char
lastc= c;
}//end inner if
}//end outer if

if (c != ' ') {//if c isn't a space don't worry about it
putchar(c);
lastc =c;
}//end if
}//end while

return 0;
}
The problem I'm having is that when I run the program, I get no
execution, just returned to a prompt. However, when I run gdb on it
(even if I just "run" the program within gdb) it works, and even does
what I expected it to. Can anyone explain this one to me?

crr
Nov 14 '05 #1
12 2120
On Mon, 05 Jul 2004 17:40:30 -0700, Chris Readle <c.******@cox.net>
wrote in comp.lang.c:
Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:
/************************************************** ****************************
* K&R2 Exercise 1-9
* Write a program to copy its input to its output, replacing strings
of blanks
* with a single blank.
************************************************** ****************************/
#include <stdio.h>

int main(void) {

int c= 0, lastc= 0;

while((c= getchar()) != EOF) {

if (c == ' ') {
if (lastc != ' ') {//if c *is* a space and lastc is
putchar(c);//*not* a space, print the char
lastc= c;
}//end inner if
}//end outer if

if (c != ' ') {//if c isn't a space don't worry about it
I hope you know that the line above could be replaced with:
else { putchar(c);
lastc =c;
}//end if
}//end while

return 0;
}
The problem I'm having is that when I run the program, I get no
execution, just returned to a prompt. However, when I run gdb on it
(even if I just "run" the program within gdb) it works, and even does
what I expected it to. Can anyone explain this one to me?

crr


Does your input contain a newline? In C it is implementation defined
whether the final line of output to a text stream requires a final
'\n' or not. Some implementations will not output the final line of
text to the display device if it does not end in a newline.

Try adding:

putchar('\n');

....just above the return from main().

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #2
Jack Klein wrote:
On Mon, 05 Jul 2004 17:40:30 -0700, Chris Readle <c.******@cox.net>
wrote in comp.lang.c:

Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:
/************************************************** ****************************
* K&R2 Exercise 1-9
* Write a program to copy its input to its output, replacing strings
of blanks
* with a single blank.
************************************************ ******************************/
#include <stdio.h>

int main(void) {

int c= 0, lastc= 0;

while((c= getchar()) != EOF) {

if (c == ' ') {
if (lastc != ' ') {//if c *is* a space and lastc is
putchar(c);//*not* a space, print the char
lastc= c;
}//end inner if
}//end outer if

if (c != ' ') {//if c isn't a space don't worry about it

I hope you know that the line above could be replaced with:
else {

Yes, I knew that, but I'm trying to follow the book closely and since it
hasn't covered else yet...
putchar(c);
lastc =c;
}//end if
}//end while

return 0;
}
The problem I'm having is that when I run the program, I get no
execution, just returned to a prompt. However, when I run gdb on it
(even if I just "run" the program within gdb) it works, and even does
what I expected it to. Can anyone explain this one to me?

crr

Does your input contain a newline? In C it is implementation defined
whether the final line of output to a text stream requires a final
'\n' or not. Some implementations will not output the final line of
text to the display device if it does not end in a newline.

Try adding:

putchar('\n');

...just above the return from main().

Well, the input *would* contain a newline, but when it has the problem
previously described, I don't get to input anything. Basically, I call
the program, press enter and am immediately returned to the prompt.

I have done some further research on this, and I have discovered that if
I start a new instance of the shell, it runs just dandy the first time,
but subsequent runs return to the prompt without allowing any input.

I tried adding the newline just before the return statement in main(),
but all that does is put an additional newline on the screen when I call
the program.

crr
Nov 14 '05 #3
On Mon, 05 Jul 2004 17:40:30 -0700, Chris Readle wrote:
Can anyone explain this one to me?


At a guess- the exec is called test. You're running it by typing 'test' in
the command line.

Try 'which test' - somehow I don't think you're running the program you
think you're running.
Nov 14 '05 #4
Ori Bernstein wrote:
On Mon, 05 Jul 2004 17:40:30 -0700, Chris Readle wrote:

Can anyone explain this one to me?

At a guess- the exec is called test. You're running it by typing 'test' in
the command line.

Try 'which test' - somehow I don't think you're running the program you
think you're running.

Actually, the executable is exer1-10.exe. And, while I have both
GNU/Linux(Fedora I think right now, though it might be Debian or
Mandrake....I forget) FreeBSD (which I mostly use as my main partition)
partitions on my system, I'm doing this coding on my Windows partition,
so which wouldn't get me very far. ;)

Thanks for the suggestion, though.

crr
Nov 14 '05 #5
Chris Readle wrote:
Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:
[...] The problem I'm having is that when I run the program, I get no
execution, just returned to a prompt. ... Can anyone explain this one to me?


Your code executes properly. If you are having a problem, it is
probably with your method of using your compiler.
Nov 14 '05 #6
Chris Readle <c.******@cox.net> wrote in message news:<hxmGc.19851$Qj6.8180@fed1read05>...
Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

<snipped>
I compiled your program using gcc-2.95 and executed it.
It works just fine if that comforts you :-)
-Anjali
Nov 14 '05 #7
On Mon, 05 Jul 2004 19:15:43 -0700, Chris Readle <c.******@cox.net>
wrote:
I have done some further research on this, and I have discovered that if
I start a new instance of the shell, it runs just dandy the first time,
but subsequent runs return to the prompt without allowing any input.

From the viewpoint of comp.lang.c, you program is fine ;-) So, the
problem must be something in your environment. You might want to post
the question on a newsgroup which deals with whatever implementation
you're working with. <OT> How does your implementation define end of
file on your stdin (the terminal, I presume)? Is something causing an
EOF to be in the input buffer after the first execution? gdb is
probably starting a brand-new shell for each execution.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #8
Alan Balmer wrote:
From the viewpoint of comp.lang.c, you program is fine ;-) So, the
problem must be something in your environment. You might want to post
the question on a newsgroup which deals with whatever implementation
you're working with. <OT> How does your implementation define end of
file on your stdin (the terminal, I presume)? Is something causing an
EOF to be in the input buffer after the first execution? gdb is
probably starting a brand-new shell for each execution.


I've come to that same conclusion myself, so I've been using one term to
compile and then starting another one to run the freshly compiled
executable.

As it turns out from further research, gdb exhibits the same behaviour
if I try to run the program multiple times from within the same gdb
session. I'm going to fire the code over to one of my other platforms
and see if it does the same thing there, which might indicate a weakness
with my compiler (gcc on both platforms).

Anyway, thanks for the help, even though it lead into OT territory.

crr
Nov 14 '05 #9
"Jack Klein" <ja*******@spamcop.net> wrote in message
news:e1********************************@4ax.com...
On Mon, 05 Jul 2004 17:40:30 -0700, Chris Readle <c.******@cox.net>
wrote in comp.lang.c:
Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:

<snip getchar/putchar copy program>
Does your input contain a newline? In C it is implementation defined
whether the final line of output to a text stream requires a final
'\n' or not.


This aspect is not limited to output files. 7.19.2p2 says...

A text stream is an ordered sequence of characters composed into lines,
each line consisting of zero or more characters plus a terminating new-
line character. Whether the last line requires a terminating new-line
character is implementation-defined. Characters may have to be added,
^^^^****^^^^^^
altered, or deleted on input and output to conform to differing
^^^^^^^^^^^^^^^^
conventions for representing text in the host environment. ...

I take that to mean that if an implementation does indeed require said new-line, it will
either insert it or otherwise change the stream so that the last line is new-line
terminated.
Some implementations will not output the final line of
text to the display device if it does not end in a newline.


As far as ISO C is concerned, stdout is a stream like any other and the program
successfully copies the portion of stdin input that constitutes a text stream.

If the program adds a new-line, then it's adding an extranious character that was not
present in the text portion of stdin. If that particular correction needs to be made, then
the implementation is responsible for doing that. 7.19.2 says so IMO.

If it's a QoI issue then, given the input and output applicability of 7.19.2, consider...

#include <stdio.h>

int main(void)
{
int c1 = getchar();
int c2 = getchar();

if (c1 != '\n' && c1 != EOF && c2 == EOF)
{
puts("Has a text line been read or not?");
puts("");
puts("Have I already invoked UB on some implementations");
puts("which require a final new-line for input streams?");
}

return 0;
}

--
Peter
Nov 14 '05 #10
Chris Readle wrote:
Ok, I've just recently finished a beginning C class and now I'm working
through K&R2 (alongside the C99 standard) to *really* learn C.

So anyway, I'm working on an exercise in chapter one which give me
strange behavior. Here is the code I've written:
/************************************************** ****************************

* K&R2 Exercise 1-9
* Write a program to copy its input to its output, replacing strings of
blanks
* with a single blank.
************************************************** ****************************/

#include <stdio.h>

int main(void) {

int c= 0, lastc= 0;

while((c= getchar()) != EOF) {

if (c == ' ') {
if (lastc != ' ') {//if c *is* a space and lastc is
putchar(c);//*not* a space, print the char
lastc= c;
}//end inner if
}//end outer if

if (c != ' ') {//if c isn't a space don't worry about it
putchar(c);
lastc =c;
}//end if
}//end while

return 0;
}
I just did it this way..

#include <stdio.h>
int main(void) {
int c, last = 0;
while ((c = getchar()) != EOF) {
if (!(c == ' ' && c == last))
putchar(c);
last = c;
}
return 0;
}

The problem I'm having is that when I run the program, I get no
execution, just returned to a prompt. However, when I run gdb on it
(even if I just "run" the program within gdb) it works, and even does
what I expected it to. Can anyone explain this one to me?

crr


Without redirecting a file to it, the program should block on
getchar(), buffering anything you type up to newline and looping in
the while until you 'type' EOF.
--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #11
Joe Wright wrote:
#include <stdio.h>
int main(void) {
int c, last = 0;
while ((c = getchar()) != EOF) {
if (!(c == ' ' && c == last))
putchar(c);
last = c;
}
return 0;
}


Yeah, I did it this way first as well, til I realized that we hadn't
covered the logical AND operator yet, so I went back and redid it.

It seems as though the Windows shell is storing the EOF on top of the
call stack or something, and this is causing my code to run only once on
the Windows side, and then never again unless I invoke a new shell.
On my FreeBSD box it runs fine multiple times.

crr
Nov 14 '05 #12
Chris Readle wrote:
Joe Wright wrote:
#include <stdio.h>
int main(void) {
int c, last = 0;
while ((c = getchar()) != EOF) {
if (!(c == ' ' && c == last))
putchar(c);
last = c;
}
return 0;
}

Yeah, I did it this way first as well, til I realized that we hadn't
covered the logical AND operator yet, so I went back and redid it.

It seems as though the Windows shell is storing the EOF on top of the
call stack or something, and this is causing my code to run only once on
the Windows side, and then never again unless I invoke a new shell. On
my FreeBSD box it runs fine multiple times.

crr


Just trying to make it simple..

#include <stdio.h>
int main(void) {
int c, last = 0;
while ((c = getchar()) != EOF) {
if (last != ' ')
putchar(c);
else if (c != ' ')
putchar(c);
last = c;
}
return 0;
}

--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of...
2
by: arnuld | last post by:
there is a solution on "clc-wiki" for exercise 1.17 of K&R2: http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_17 i see this uses pointers whereas K&R2 have not discussed pointers...
8
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. ...
4
by: arnuld | last post by:
as i said, i have restarted the book because i overlooked some material. i want to have some comments/views on this solution. it runs fine, BTW. ------------------ PROGRAMME -------------- /*...
16
by: arnuld | last post by:
i have created solution which compiles and runs without any error/ warning but it does not work. i am not able to understand why. i thought it is good to post my code here for correction before...
19
by: arnuld | last post by:
this programme runs without any error but it does not do what i want it to do: ------------- PROGRAMME -------------- /* K&R2, section 1.6 Arrays; Exercise 1-13. STATEMENT: Write a program...
5
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any...
16
by: arnuld | last post by:
i am not able to make it work. it compiles without any error but does not work: what i WANTED: 1.) 1st we will take the input in to an array. (calling "getline" in "main") 2.) we will print...
88
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.