6-29 Esc Chars (20分)

6-29 Esc Chars (20分)
 

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

Function prt_esc_chars() gets a string which may contains esc characters, and prints the string into the standard ouput with all esc characters been replaced by a \x format combination.

For example, using printf("%s"..., a string with a \n between the words will be printed as:

Hello
World
 

But the same string will be printed by prt_esc_chars() as:

Hello\nWorld
 

Your function should be able to recognize esc characters below:

\n
\r
\t
\b
 

And all other characters below 0x20 should be printed 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.

Be aware, printf() is forbidden in the function.

函数接口定义:

int prt_esc_char(const char *s);
 

s is the string to be printed. The function returns the number of characters printed. An esc character is counted as two or three according to the characters it uses.

裁判测试程序样例:

#include <stdio.h>

int prt_esc_char(const char *s);

int main()
{
	char *line = NULL;
	size_t linecap = 0;
	getline(&line, &linecap, stdin);
	int len = prt_esc_char(line);
	printf("%d\n", len);
}

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

输入样例:

hello    world
 

There is a tab between hello and world.

输出样例:

hello\tworld\n14





int prt_esc_char(const char *a)
{
 int i;
 int count=0;
 int flag;
 int d,g;
 for(i=0;a[i]!='\0';i++)
 {
  flag=0;
  switch(a[i])
  {
   case '\n': putchar('\\');putchar('n');flag=1;count+=2;break;
   case '\r': putchar('\\');putchar('r');flag=1;count+=2;break;
   case '\t': putchar('\\');putchar('t');flag=1;count+=2;break;
   case '\b': putchar('\\');putchar('b');flag=1;count+=2;break;
  }
  if(a[i]<0x20&&flag==0)
  {
   putchar('\\');
   
   d=a[i]/16+'0';
   g=a[i]%16+'0';
   putchar(d);
   putchar(g);
   count+=3;
  }
  else
  {
   if(flag==0)
   {
   putchar(a[i]);
   count++;
  }
   
  }
 }
 return count;
 
}
int  getline(char **str, size_t *n, FILE *stream)
{
 *str=malloc(2000*sizeof(char));
 
 fgets(*str,2000,stdin);
 return 1;
}
posted @ 2020-10-19 20:52  罪梦者  阅读(1091)  评论(0)    收藏  举报