简体   繁体   中英

How to print a string, which includes special characters and was read from a file? How to print it without special characters?

I have following function:

int Printf(const char *s, int length)
{
   int i=0;
   while(i < length)      
   {
      printf("%c", s[i]);
      i++;
   }
}

But if I call it with a non null-terminated string like "Hello World\\n" which I read from a file, it prints Hello World\\n without making a new line, so it prints \\n explicitly. What is wrong with my function?

There's nothing wrong, but I guess the \\n is essentially in the string. When you write \\n inside a string in your C/C++ program the compiler will replace it with the proper linebreak. However this doesn't happen if the \\n is in your text (essentially being "\\\\n" ).

Where is the string set? Seems like you might have to handle the escaped characters yourself.

Btw. depending on your compiler you should be able to use something like this, which is a lot simplier:

printf("%*s", length, s);

Edit: Just read your comment above. You'll have to handle the \\n -> linebreak replacement yourself if you read the string from a file. printf() won't handle it for you.

Special characters are handled by the compiler, not by printf. They are converted during compile time, so

char a[] = "a\n";

becomes equivalent to

char a[] = { 'a', 13, 0 };

printf never sees "\\n", the compiler has converted that to 13 beforehand. And printf doesn't have the ability to convert special characters. When you read "Hello World\\n" from a file, you can't expect it to be converted by the compiler.

I have rewritten my function so:

int Printf(char *s, int length)
{
   int   i=0;
   char  c = '\0',
         special='\\',
         newline ='n', 
         creturn ='r', 
         tab     ='t';
   while(i < length)
   {
      if(c == special) 
      { 
         if( s[i] == newline )
            printf("\n"); 
         else if(s[i] == creturn)
            printf("\r"); 
         else if(s[i] == tab)
            printf("\t"); 
         else if(s[i] == special)
            printf("\\"); 
      } 
      else if (s[i] != '\\')
         printf("%c", s[i]); 
      c = s[i];
      i++;
   }
}

and now it does work right!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM