How do I print out % of special characters instead of "\" when printing?

Asked 2 years ago, Updated 2 years ago, 111 views

printf("hello\%"); //not like this

If I use a backslash, it's too hard to see when there are too many special characters, so I want to know another way. I get the same result as that code, but is there a way to print out % without using \% together?

c print format-string

2022-09-21 15:39

1 Answers

If you don't want to use a format specifier, You can solve it by writing special characters twice, such as %%

printf("printf(\"hello%%%%\"): hello%%\n");
//or
printf("printf(\"hello%%c\"): hello%c\n", '%');

Output:

printf("hello%%"): hello%
printf("hello%c"): hello%

You have to be careful when you use it, but you don't use it right away in printf Depending on how you print it out, you might get different results.

int main(int argc, const char * argv[]) {
    char a[5];
    strcpy(a, "%%");

    printf("printf(a): ");
    printf(a);

    printf("\nprintf(\"%%s\", a): %s\n", a);
}

Output:

printf(a): %
printf("%s", a): %%
int main(int argc, const char * argv[]) {
    char a[5];
    strcpy(a, "%");

    printf("printf(a): ");
    printf(a);

    printf("\nprintf(\"%%s\", a): %s\n", a);
}

Output:

printf(a): 
printf("%s", a): %


2022-09-21 15:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.