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

丶灬走出姿态 提交于 2019-12-24 09:50:02

问题


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. }



来源:https://stackoverflow.com/questions/4382775/how-can-i-display-the-characters-t-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!