【问题标题】:Print out entities in a char array打印出 char 数组中的实体
【发布时间】:2014-05-10 06:52:47
【问题描述】:

是否可以打印出 char 数组中的实体,以便实际看到字符串终止符 \0 和换行符 \n 的每个字符...例如?

假设一个字符串由以下内容组成

 abkdfkdfmdfier\nkdfdfkdkf\n\0

我想通过 std::cout 查看所有内容

【问题讨论】:

  • 你想要的输出是什么?
  • 给我一些时间......
  • 一切 - 包括 \0 和 \n

标签: c++ arrays char


【解决方案1】:

我认为您应该编写一个函数,在旧字符串的基础上创建一个新字符串并将'\n','\0' 字符更改为"\\n","\\0" 字符串。

我可能有一些错误,但我的主要想法是这个。

希望这会有所帮助。

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>

char *mstr;

void newStr(char *str){
   char *buf;
   if((buf=(char*)malloc(strlen(str)+4)*sizeof(char))==NULL){
      printf("err in allocating buffer");
      getch();
      exit(1);
   }
   register unsigned int i;
   for(i=0;i<strlen(str) & i<30000;i++){
      if(str[i]=='\n'){
         str[i]=0;
         strcpy(buf,"\\n");
         strcat(buf,(char*)(str+i+1));
         strcat(str,buf));
      }
   }
   strcat(str,"\\0");
}
void main(){
   clrscr();
   strcpy(mstr,"this is a\n test\nggg\0");
   printf("form1:\n%s",str);
   newStr(str);
   printf("\nform2:\n%s",str);
   getch();
}

【讨论】:

  • 欢迎您,但我认为这个想法是正确的,您需要稍微改变一下。但我的笔记本电脑中没有任何编译器。
【解决方案2】:

您需要检查字符串中字符的 ASCII 码。

for (int i=0; i<strlen(string)+1; i++) {
    if (printable(string[i])) cout << string[i];  // If normal char like abc ' ' 123 !@#
    else {
        int code = string[i];
        // i will write for '\n' for example
        switch (code) {
            case 0x0A : cout << "\\n";
                        break;
            // etc...
        }
     }
 }

现在,printable(char c) 将检查 ascii 值是否是一些可打印的字符(并检查其中是否不是像 \0\n 等特殊字符。

http://www.asciitable.com/index/asciifull.gif

http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters

【讨论】:

    【解决方案3】:

    这是使用isprint 和流格式化程序的解决方案:

    #include <cctype>
    
    void print_escaped(char chr) {
        if (std::isprint(chr)) {
            std::cout << chr;
        } else {
            switch(chr) {
            case '\0': std::cout << "\\0"; break;
            case '\r': std::cout << "\\r"; break;
            case '\n': std::cout << "\\n"; break;
            case '\t': std::cout << "\\t"; break;
            default: // other non printable chars
                std::cout << "\\x" << std::setfill('0') << std::setw(2) << std::hex << (int)chr;
                break;
            }
        }
    }
    
    int main() {
        std::string text = "abkdfkdfmdfier\nkdfdfkdkf\n";
        text.push_back('\0'); // don't use it in a raw string !
        text.push_back('\x03');
        std::for_each(text.begin(), text.end(), print_escaped);
        std::cout << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2012-10-02
      • 2012-10-29
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多