6-30 Read Esc Chars (30分)

6-30 Read Esc Chars (30分)
 

Esc characters are represented as \x in C string, such as \n and \t.

Function read_esc_chars() reads a line that may contains esc character representations from the standard input and parses all those esc character representations into esc characters.

For example, a string:

This is \t a test.
 

will be converted as:

This is    a test.
 

There is a tab between is and a.

Your function should be able to recognize esc characters below:

\n
\r
\t
\b
 

And all other characters below 0x20 will be presented as:

\hh
 

where hh is the hexadecimal of the value, all letters in capital. For a value below 0x10, a leading 0 is needed to keep two positions.

And as a C string, 0x00 will not be part of the string but the terminator.

函数接口定义:

int read_esc_char(char *line, int len);
 

line is the place that can hold the string read from user's input.

len is the size of line.

The function reads a whole line from the standard input and returns number of characters in the converted string. If the inputed line is longer than the place, only the characters that can be safely placed in the place can be read in.

裁判测试程序样例:

#include <stdio.h>

int read_esc_char(char *line, int len);

static const LINE_LEN = 80;

int main()
{
	  char line[LINE_LEN];
    printf("%d\n", read_esc_char(line, LINE_LEN));
    printf("%s\n", line);
}

/* 请在这里填写答案 */
 

输入样例:

hello\tworld
 

输出样例:

11
hello   world
 

There is a tab between hello and world.

 

 

 

int read_esc_char(char *line, int len)
{
 int count=0;
 char c;
 int d,g;
 while((c=getchar())!='\n'&&count<len-1)
 {
   if(c=='\\')
   {
    c=getchar();
    if(c=='t'||c=='b'||c=='n'||c=='r')
    {
     switch(c)
     {
     case 't': c='\t';break;
     case 'b': c='\b';break;
     case 'n': c='\n';break;
     case 'r': c='\r';break;
       }
     line[count++]=c;
     
    }
  else
  {
   
   d=(c-'0')*16;
   g=getchar();
   if(g>='0'&&g<='9')
   {
    d+=g-'0';
   }
   else
   {
       g=g-'A'+10;
    d+=g; 
   }
   line[count++]=d;
   
  }
    
   }
   else
   line[count++]=c;
  
  
 }
 line[count]='\0';
 return count;
}
posted @ 2020-10-19 20:53  罪梦者  阅读(498)  评论(0)    收藏  举报