0

Going through K&R, I'm trying to get my head around C. I want to write a program that prints on the screen the user's previous line, unless the character was "a".

int main(){

int c;

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

     if(c!='a')
            putchar(c);
}
return 0;
}

Yes, the program isn't much. But it won't work as intended. Do I need to use the ASCII value of the character "a", because the above code just prints all the letters regardless of being a or not.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 3
    I just ran the code and it works fine for me? – Giltech Jul 18 '11 at 23:55
  • So it doesnt print the character a when a is typed? –  Jul 18 '11 at 23:56
  • correct the output I receive is print letter the entered letter for all but the letter a, that was with a direct copy and paste of your code. It does print out the carriage return, if you enter a string of letters **lalala** it will output **lll** as using a while loop and getchar it will keep looping through input buffer till empty. That is also why you see carriage return – Giltech Jul 18 '11 at 23:58
  • ah. I made a really stupid mistake. It works fine. Write your reply as an answer and I'll mark it as correct. –  Jul 19 '11 at 00:05
  • 1
    I think you are confusing the terminal echoing your input and what your program is outputting. Try "echo lalala | ./test > result" and then "cat result". – Nemo Jul 19 '11 at 00:08

1 Answers1

1

The code should work as specified, but what you will find is that using getchar with the while loop will print a carriage return when a is entered. This is because in the current implementation getchar will keep reading the input buffer till it is empty, if you wanted to stop this happening you could flush it in the if statement.

Entering a string of text at the moment will print the string removing any *a*s

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Giltech
  • 596
  • 5
  • 7
  • 1
    Sorry, but no. [getchar](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getchar.html) returns an int; [putchar](http://pubs.opengroup.org/onlinepubs/9699919799/functions/putchar.html) takes an int. – Nemo Jul 19 '11 at 00:06