Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c programming language exercise 1.10: what is wrong with my solution?

Tags:

c

I'm trying to do exercise 1-10 from the C Programming Language. The idea is to create a program where the output equals the input, however, if a tab is printed, it should print \t instead of the actual tab. It also suggests doing the same with backspace/backslash, but I am trying to get it to work with just a tab before moving forwards.

I determined the value of a tab to be 9, so I came up with this code. I am confused as to why this doesn't work - it seems like a straightforward method of solving the problem. If the character getchar receives has a value equal to 9, which a tab would, then output \t in plain text. I would love to be smacked on the head for whatever has lead me barking up the wrong tree with the following code. I have seen some people post solutions here, yet I am still confused as to what minor detail is causing this to fail.

   #include <stdio.h>

    main(){

    int c;
    while ((c = getchar()) != EOF) {
        if ((c == '\t') == 9) putchar("\t");
        else purchar(c);
    }
    }

That brings the following compilation error

tenth.c: In function 'main':
tenth.c:7:35: warning: passing argument 1 of 'putchar' makes integer from pointe
r without a cast
     if ((c == '\t') == 9) putchar("\t");
                                   ^
In file included from tenth.c:1:0:
c:\mingw\include\stdio.h:645:43: note: expected 'int' but argument is of type 'c
har *'
 __CRT_INLINE __cdecl __MINGW_NOTHROW  int putchar(int __c)
                                           ^
C:\Users\*\AppData\Local\Temp\ccC4FPSb.o:tenth.c:(.text+0x18): undefined ref
erence to `purchar'
collect2.exe: error: ld returned 1 exit status

I've also tried

main(){

int c;
while ((c = getchar()) != EOF) {
    if (c == '\t') putchar("\t");
    else purchar(c);
}
}
like image 532
cfinspan Avatar asked Dec 05 '22 17:12

cfinspan


1 Answers

There's a difference between ' and " in C:

  • "\t" creates a C-style string of type char[2] containing the characters \t (tab) and \0 (the NUL-terminating character).
  • '\t' is a single character of type int.

putchar takes an int parameter and prints out a single character. You should use (assuming your goal is to print the message \t to the user and not a tab character):

putchar('\\');  // Print the backslash (it must be escaped)
putchar('t');   // Print the t

Note that the \ character is special and needs to be escaped with an extra \ (so '\\' is a single \ character of type int).

like image 69
Cornstalks Avatar answered May 25 '23 07:05

Cornstalks