Char const for backslash

S

Sathyaish

In trying to replace character literals for their char constant, I am
having difficulty printing the char constant for backslash. It instead
prints the char literal. How do I resovle this?


#include <stdio.h>

/*A program that reads keyboard input and reproduces it on the monitor
with some modifications.
It displays all newline character occurences as \n, tabs as \t and
backslashes as \\.

Basically, it replaces some of the characters with their character
constants.

*/

void main()
{
int c;

while ((c=getchar()) != EOF)
{

if ((char)c=='\n')
{
printf("\\n");
putchar(c);
}
else if ((char)c=='\t')
{
printf("\\t");
}
else if ((char)c=='\\')
{
printf("\\");
}
else
{
putchar(c);
}

} //end of while loop

} // end of main


I want that when I type a backslash, the output must be replaced with
\\, the character constant for backslash.
 
J

Joona I Palaste

Sathyaish said:
In trying to replace character literals for their char constant, I am
having difficulty printing the char constant for backslash. It instead
prints the char literal. How do I resovle this?

Try printf("\\\\").
 
M

Martin Dickopp

In trying to replace character literals for their char constant, I am
having difficulty printing the char constant for backslash. It instead
prints the char literal. How do I resovle this?


#include <stdio.h>

/*A program that reads keyboard input and reproduces it on the monitor
with some modifications.
It displays all newline character occurences as \n, tabs as \t and
backslashes as \\.

Basically, it replaces some of the characters with their character
constants.

*/

void main()

int main (void)
{
int c;

while ((c=getchar()) != EOF)
{

if ((char)c=='\n')

Why do you cast `c' to `char'? It's completely unnecessary. Before it is
compared to the `int' constant '\n', the result of `(char)c' is promoted
to `int' anyway.
else if ((char)c=='\\')
{
printf("\\");

\\ in a string or character literal represents a single \, so "\\" is a
string literal consisting of a single backslash character. You want
"\\\\".

Martin
 
S

Sathyaish

Thank you very much, Joona and Martin. You're so right.

Regards,
Sathyaish Chakravarthy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top