LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Newbie C Question from K&R (https://www.linuxquestions.org/questions/programming-9/newbie-c-question-from-k-and-r-421478/)

noir911 03-04-2006 02:10 AM

Newbie C Question from K&R
 
I been doing some C coding and have copied the following program from K&R. It compiles OK but doesn't do what it's supposed to - converting uppercase (from STDIN) to lowercase (to STDOUT).

Here's the code,

Code:


#include <stdio.h>
#include <ctype.h>

int main(void)

/* this program converts uppercase to lowercase */

{

int c;
while (( c == getchar()) != EOF)
    putchar(tolower(c));
return 0;
}


jlliagre 03-04-2006 03:34 AM

There's a typo in this program, double check how 'c' variable is used.

kshkid 03-04-2006 03:40 AM

Quote:

Originally Posted by jlliagre
There's a typo in this program, double check how 'c' variable is used.

i could see a bug only here;
Code:

while (( c == getchar()) != EOF)
should be
Code:

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

jlliagre 03-04-2006 04:02 AM

The original program was undoubtly correct. I'm not expecting Ritchie or Kernighan falling in such a newbie trap and publish buggy examples.

gerlano 03-04-2006 02:49 PM

C example
 
If you post the output you get when you run the program against a small sample I may be able to help.



Reading the code you create an unitialised variable c, then in the while statement do a boolean comparison against getchar(), which is then compared to EOF to check for the end of file. At no stage is the value read in by stdin actually assigned to the variable c.

Looking at the code I have to agree that using == to test against the getchar() function will result in unpredictable behaviour. Try changing it as kshkid suggested.

I have run the program through VC7, and on debugging got an uninitialised variable error. Only way this program is going to run is if you change the code to read:

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

From experience we all make mistakes in write example code, and it is usually the simple things that get through as we presume they work and don't test.

noir911 03-04-2006 05:17 PM

Quote:

Originally Posted by kshkid
i could see a bug only here;
Code:

while (( c == getchar()) != EOF)
should be
Code:

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

Sorry guys, my bad. I made a mistake exactly right here. It's working fine now.

Sorry once again.


All times are GMT -5. The time now is 12:13 AM.