Printf ignores single backslash '\'

I have this code:

int main(int argc, char * argv[]) { int i; printf("%d%s",argc,argv[1]); return 0; } 

If I ran 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= ".

+4
source share
4 answers

Update for editable question :

Include the command line argument in quotation marks:

  $ a.out "a\=b=" 

The quotes do not allow the shell to interpret the shell argument, so this string is passed to your program. I am using csh / bash ..works with both.

Alternatively, you can "escape" from \ with another and skip double quotes:

  $ a.out a\\=b= 

Previous answer to the original question :

Yes, use two \ :

 char a[]="a\\=b="; 

outputs:

 a\=b= 

Explanation

\ is an escape character used to indicate a special sequence of characters, therefore, for example, \t indicates a tab. If you want to actually print \t , you need to "avoid" this \ with another \ . See this example and conclusion:

 printf("\t-->Hi\n"); /* print regular tab via \t */ printf("\\t-->Hi\n"); /* want to print "\t", not tab ..so we use two \\ */ 

that leads to:

  -->Hi \t-->Hi 

This is not unique to the printf() function and not to C, whether languages ​​can use backslashes to indicate "escape sequences" in strings.

+9
source

printf() does not ignore your only backslash, this is how C lines are constructed. A backslash is an escape character that points to some character that is not easy to type in a line, such as a newline ( \n ) or nested quote ( \" ). Therefore, to include a backslash, you must include two backslashes ( \\ ). This applies to all lines and does not apply to printf() .

+7
source

\ is the escape character in lines in C. You use it to access a special character, such as a newline ( \n ). If you want to access \ as a character, you also need to avoid it: \\ .

+1
source

\\ is what reads as \ in C

\ is the only character used inside char or a string in C to denote another character or string of characters. What is meant by the name "escape".

Since it was used in this way, it was necessary to include a backslash as one of the characters that succumb to this approach.

Some other sequences: \ n new line tab \ t \ v vertical tab \ ringtone

0
source

All Articles