Thread: KnR, Ch1, ex 1-10

  1. #1
    Registered User
    Join Date
    Nov 2005

    KnR, Ch1, ex 1-10

    Hello, I'm reviewing KnR after not having done much programming in about 7 years. I just encountered some behavior I can't quite figure out in the program I made for ex. 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 backspaces visible in an unambiguous way".)

    Can anybody tell me why, when typing "\" & hitting return the output of the code below should be this? (the tab handling statements seem to be just fine)


    hello feck


    while(   (c=getchar())  !=EOF  ){
        if (c=='\t'){
        if (c!='\t'){
          if(c=='\\') printf("hello ");{
    		if(c!='\\') printf("feck ");
      return 0;
    thank you in advance

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Despite your indentation, your code reads as
        if (c!='\t'){
          if(c=='\\') printf("hello ");
             if(c!='\\') printf("feck ");
    With a \, you get hello printed, with the if(c=='\\'), because \ is not equal to a tab
    With a newline, you get feck printed, because newline isn't a tab, and it isn't \\ either

    Why is if(c=='\\') inside another if statement?

    Shouldn't it be
    if ( c == '\t' )
    if ( c == '\\' )
    if ( c == '\b' )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading a file
    By nhubred in forum C++ Programming
    Replies: 3
    Last Post: 05-21-2009, 11:34 AM
  2. A-Star Pathfinding
    By mike_g in forum General AI Programming
    Replies: 1
    Last Post: 08-05-2007, 04:18 PM
  3. Segmentation Fault
    By Lost__Soul in forum C Programming
    Replies: 46
    Last Post: 04-28-2003, 04:24 AM
  4. Scheduling Algo
    By BigDaddyDrew in forum C++ Programming
    Replies: 41
    Last Post: 03-08-2003, 11:00 AM
  5. Heaps...
    By Nutshell in forum C Programming
    Replies: 14
    Last Post: 04-23-2002, 08:54 AM