how can I display the characters \\t in a string?

2019-07-30 00:19发布

问题:

Evening all, What would be the correct key sequence to display "\t" as a literal value, and not a text format?

My code is below...

Thanks a bunch.

main()
{

  int c;

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

      if (c == '  ')
          c = "\t";
    putchar(c);
    }

}

So to clarify, I do not want to have a tabbed string, but instead display the characters \t.

回答1:

You can escape a backslash with another backslash, i.e. "\\t".

Incidentally, you're trying to assign a string (i.e. more than one character) to an int. This doesn't make sense!



回答2:

Wouldn't you really want something like this instead?

if (c == '\t')
{
    printf("\\t");
}


回答3:

Escape the backslash, thus "\\t".



回答4:

To have a backslash in a character/string constant interpreted literally, you have to escape it with another backslash. Also, a single call to putchar() will not be enough since you have to print two characters. With this you get:

putchar('\\');
putchar('t');


回答5:

You need to escape the escape, as follows:

printf("\\t");

This will print \t as you want.



回答6:

Actually "\t" requires two characters to display.

main()
{

  int c;

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

      if (c == '  ') {
       putchar('\\');
       putchar('t');
      }
  }

would be one way of doing it. }