I have this code :
int main(int argc, char * argv[])
{
int i;
printf("%d%s",argc,argv[1]);
return 0;
}
If I run this code as a.out a\=b=
.I am using C-shell
Its output is "a=b=
" is there any way that its output can be changed to "a\=b=
".
Update for edited question:
Enclose your command line argument in quotes:
$ a.out "a\=b="
The quotes prevent the shell from interpreting the command line argument in any way, so just this string is passed to your program. I use the csh
/bash
..works with both.
Alternatively, you can "escape" the \
with another one and skip the double quotes:
$ a.out a\\=b=
Previous answer to original question:
Yes, use two \
:
char a[]="a\\=b=";
outputs:
a\=b=
Explanation:
\
is an escape character used to indicate a special character sequence, so for instance \t
indicates a tab. If you want to actually print \t
, you need to "escape" this \
with another \
. See this example and output:
printf("\t-->Hi\n"); /* print regular tab via \t */
printf("\\t-->Hi\n"); /* want to print "\t", not tab ..so we use two \\ */
which results in:
-->Hi
\t-->Hi
This is not unique to the printf()
function, nor really to C, may languages use the backslash to indicate "escape sequences" in strings.
printf()
is not ignoring your single backslash, it's the way C strings are parsed. A backslash is an escape character to indicate some character that is not easily entered in a string, for example a newline (\n
) or embedded quote (\"
). Consequently, to include a backslash you must include two backslashes (\\
). This is for all strings, and not related to printf()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With