C程序设计语言-练习3-2

  练习3-2 编写escape(s, t),将字符串t复制到字符串s中,并在复制过程中将换行符、制表符、等不可以见字符分别转换为\n,\t等相应的可见的字符序列。在编一个具有相反功能的函数,在复制过程中将转义字符序列转换为实际字符。

 

1)为了简化程序,假设t的空间足够大。

2)只编写了前一个程序。

3)只处理换行符,制表符。

 

 1 #include <cstdio>
 2 
 3 using namespace std;
 4 
 5 //copy s to t
 6 void Escape(char s[], char t[])
 7 {
 8     int j = 0;
 9     for(int i = 0; s[i] != '\0'; i++)
10     {
11         switch(s[i])
12         {
13             case '\n'
14                 t[j++= '\\';
15                 t[j++= 'n';
16                 break;
17             case '\t':
18                 t[j++= '\\';
19                 t[j++= 't';
20                 break;
21             default:
22                 t[j++= s[i];
23         }
24     }
25     t[j] = '\0';
26 }
27 
28 int main()
29 {
30     const int SIZE = 10;
31     char s[SIZE];
32 
33     int i = 0;
34     for(int c; i != SIZE-1 && (c = getchar()) != EOF; i++)
35     {
36         s[i] = c;
37     }
38     s[i] = '\0';
39 
40     
41     char t[2*SIZE+1]; 
42     Escape(s, t);
43     for(int j = 0; t[j] != '\0'; j++)
44     {
45         putchar(t[j]);
46     }
47     return 0;    
48 }
49 


 

posted on 2010-07-23 10:45  ewee  阅读(371)  评论(0编辑  收藏  举报

导航