Why is percentage character not escaped with backs

2020-02-10 02:23发布

The printf() documentation says that if someone wants to print % in C, he can use:

printf("%%")

Why is it not:

printf("\%")

as with other special characters?

4条回答
孤傲高冷的网名
2楼-- · 2020-02-10 02:57

The backslash is processed by the compiler when interpreting the source text of the program. So the common result is that the source text "\%" produces a string containing ”%”.

The format string is interpreted by the printf routine, so it processes the characters passed to it. By this time, the backslash is no longer present, so printf never sees it.

Technically, \% is not legal in a string literal. The character \ starts an escape sequence, and the only legal escape sequences are listed in C 2011 6.4.4.4 1. They are \ followed by ', ", ?, \, a, b, f, n, r, t, v, one to three octal digits, x and hexadecimal digits, u and four hexadecimal digits, or U and eight hexadecimal digits.

If printf had been designed so that a backslash would escape a percent, then you would have to pass it a backslash by escaping the backslash in the source text, so you would have to write:

printf("\\%");
查看更多
来,给爷笑一个
3楼-- · 2020-02-10 02:59

Because the % is handled by printf. It is not a special character in C, but printf itself treats it differently.

查看更多
Explosion°爆炸
4楼-- · 2020-02-10 03:07

The convention is that special characters escape themselves. So, rather than using backslash to escape the percent, it escapes itself. (Note that to pass a backslash to printf, you'd have to write the string literal as "\\%".)

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-10 03:07

You can do it !!!!!

#include <iostream>
#include <string>
#include "stdio.h"
using namespace std;



int main(int argc, char **argv)
{


    printf("hhhhhhh %s \n","\%");
    printf("hhhhhhh  \n");

    return 0;
}

The problem exist with printf and differ from the compiler you use .. With wxWidget lib you can not use printf with two escape sequences

printf(" xxxxxx  \0x81  xx \0x82 xx \n");

don t go. But if you use

printf(" xxxxxx  %s  xx %s \n","\0x81","\0x82"); 

you are right. A plus

查看更多
登录 后发表回答