1

Going through K&R 'The C Programming Language' and on exercise 1-10 where you are asked to replace each tab, backspace, and backslash with two backslashes. I noticed that my console is returning only '\'

example of my code

#include <stdio.h>

main ()
{

 int c;

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


  switch (c) {
      case '\t': putchar ('\\');  break;
      case ' ': putchar ('\\');  break;
      case '\\': putchar ('\\'); break;
      default:   putchar (c);
  }
 }

}

to fix it I have to put:

  switch (c) {
      case '\t': putchar ('\\'); putchar ('\\') break;

is this something to do with windows and character literals or am I missing something? Just wondering if this is an indication that I need to do some reading on how programming in c is going to be different for me on windows (even using gcc compiler)

1 Answers1

3

You're falling victim to what many in the regex business call blackslash hell.

Because traditionally \ is used to denote escape sequence, escaping it can (understandably) get a little confusing.

For every \ that you want to print, you need to escape it with another \.

display -> write
----------------
  \     -> \\
  \\    -> \\\\

etc. ad nauseum

Unfortunately \\\\ isn't a char, so you won't be able to use putchar, but you'll want 4 slashes. You can use puts("\\\\") or use your current approach with two putchar('\\').

erip
  • 16,374
  • 11
  • 66
  • 121