-
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
-
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' )