Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf ignores single backslash '\'

Tags:

c

string

printf

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=".

like image 610
nav_jan Avatar asked Dec 04 '22 03:12

nav_jan


2 Answers

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.

like image 131
Levon Avatar answered Dec 05 '22 17:12

Levon


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().

like image 41
FatalError Avatar answered Dec 05 '22 16:12

FatalError