Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   Printing escape sequences using printf()? (http://www.programmingforums.org/showthread.php?t=6792)

bivhitscar Nov 2nd, 2005 8:34 PM

Printing escape sequences using printf()?
 
Is it possible to print the escape sequence representation of a nonprinting character using printf()? ie. print "\n" instead of actually printing the newline itself.

I am trying to get a loop to read a string and print each character with it's equivalent ascii code. But this all turns to shit mainly with the newline character. Aside from making a kinda long if statement to filter the possibilites, any suggestions?

nindoja Nov 2nd, 2005 8:37 PM

[code]printf("\\n");[code]
Basically, escape the backslash, so the escape sequence isn't seen.

bivhitscar Nov 2nd, 2005 8:48 PM

Quote:

Originally Posted by nindoja
:

printf("\\n");
Basically, escape the backslash, so the escape sequence isn't seen.

That only works when I know what character is coming.

This is the code I'm using:

:

for (i = 1; i <= length; i++)
  {
    printf("%c = %3d, ", string[i - 1], string[i - 1]);

    if (i % 8 == 0)
      printf("\n");
  }


That basicaly says, read the current element of the array, print the character and print it's ascii code. The if statement is just for formatting purposes.

Ideally, I just want a simple if else that says if ch == isspace() print the escape sequence instead of the actual character, else print the character. Am I making any sense?

bivhitscar Nov 2nd, 2005 8:56 PM

Actually, after reviewing what characters would actually pop up in real input, it's only two - a fair bit easier than I first thought. Although, I'd still like to hear if it's possible. :)

InfoGeek Nov 3rd, 2005 3:08 AM

You can do something like
:

if(ch=='\n')
  printf("<new-line> - %3d",ch);
else if(ch==' ')
  printf("<space> - %3d",ch);


bivhitscar Nov 3rd, 2005 10:08 PM

Quote:

Originally Posted by InfoGeek
You can do something like
:

if(ch=='\n')
  printf("<new-line> - %3d",ch);
else if(ch==' ')
  printf("<space> - %3d",ch);


Yeh, I just ended up using a switch. Thanks though. :D


All times are GMT -5. The time now is 11:02 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC