KnR, Ch1, ex 1-10

This is a discussion on KnR, Ch1, ex 1-10 within the C Programming forums, part of the General Programming Boards category; Hello, I'm reviewing KnR after not having done much programming in about 7 years. I just encountered some behavior I ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    1

    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

    ----------------------------

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

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    Despite your indentation, your code reads as
    Code:
        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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 10:00 AM
  5. Heaps...
    By Nutshell in forum C Programming
    Replies: 14
    Last Post: 04-23-2002, 08:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21