简体   繁体   English

如何打印从文件中读取的包含特殊字符的字符串? 如何不带特殊字符打印?

[英]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. 但是,如果我使用从文件中读取的非空终止字符串(如“ Hello World \\ n”)来调用它,则它会打印Hello World \\ n而不会产生新行,因此会显式打印\\ n What is wrong with my function? 我的功能出了什么问题?

There's nothing wrong, but I guess the \\n is essentially in the string. 没什么错,但是我想\\n本质上是字符串。 When you write \\n inside a string in your C/C++ program the compiler will replace it with the proper linebreak. 当您在C / C ++程序的字符串中写入\\n ,编译器将使用适当的换行符替换它。 However this doesn't happen if the \\n is in your text (essentially being "\\\\n" ). 但是,如果\\n在您的文本中(基本上是"\\\\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. 如果您从文件中读取字符串,则必须自己处理\\n >换行符。 printf() won't handle it for you. printf()不会为您处理。

Special characters are handled by the compiler, not by printf. 特殊字符由编译器处理,而不由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. printf从未看到“ \\ n”,编译器已将其预先转换为13。 And printf doesn't have the ability to convert special characters. 而且printf不能转换特殊字符。 When you read "Hello World\\n" from a file, you can't expect it to be converted by the compiler. 从文件中读取“ Hello World \\ n”时,不能指望编译器会转换它。

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! 现在确实可以正常工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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