大家好,我在学习c语言,遇到一个问题不知道哪里出了毛病!请看内容!
c语言教科书里面第三章有道题!我写了如下代码:代码1是去掉转义字符
代码2是增加转义字符
在测试的时候 我用了字符串 char text1[50] = "\aHello,\\n\n\tWorld! Mistakee\b was \"Extra 'e'\"!\\n";
结果输出不正常了!!不知道错在哪里,请坛子里的大神给指点下啊!
代码1:
程序代码:
void escape(char *s,char *t){ int count = 0; while( *t != '\0') { switch( *t ) { case '\n': *(s + (count++) ) = '\\'; *(s + count ) = 'n'; break; case '\t': *(s + (count++) ) ='\\'; *(s + count ) = 't'; break; case '\b': *(s + (count++) ) = '\\'; *(s + count ) = 'b'; break; case '\f': *(s + (count++) ) = '\\'; *(s + count ) = 'f'; break; case '\r': *(s + (count++) ) = '\\'; *(s + count ) = 'r'; break; case '\v': *(s + (count++) ) = '\\'; *(s + count ) = 'v'; break; case '\\': *(s + (count++) ) = '\\'; *(s + count ) = '\\'; break; case '\"': *(s + (count++) ) = '\\'; *(s + count ) = '\"'; break; default: /* This is not a special character, so just copy it */ *(s + count ) = *t; break; } count++ ; t++; } *(s + count ) = *t ; }
代码2:
程序代码:
void unescape(char *s,char *t ){ int count = 0; while( *s != '\0') { switch( *s ) { case '\\': switch ( *(++s) ){ case 'n': *(t + count ) = '\n'; break; case 't': *(t + count ) = '\t'; break; case 'b': *(t + count ) = '\b'; break; case 'f': *(t + count ) = '\f'; break; case 'r': *(t + count ) = '\r'; break; case 'v': *(t + count ) = '\v'; break; case '\\': *(t + count ) = '\\'; break; case '\"': *(t + count ) = '\"'; break; default: *(t + (count++) ) = '\\'; *(t + count ) = *s; break; } break; default: /* This is not a special character, so just copy it */ *(t + count ) = *s; break; } count++ ; s++; } *(t + count ) = *s ; }
代码3 测试:
程序代码:
int main(){ char *s= "12132343245235426546qefwqefasdfwefasfwefasdfaseqefq"; char text1[50] = "\aHello,\\n\n\tWorld! Mistakee\b was \"Extra 'e'\"!\\n"; char *text2 = " "; printf("%s\n",text1); /* 输出源串*/ escape( s,text1); printf("%s\n",s); /* 输出取消转义字符之后的串*/ unescape( s,text2); printf(" %s\n",text2);/* 输出增加转义字符之后的串*/ getch(); return 0; }
[ 本帖最后由 erick8888 于 2015-6-23 14:46 编辑 ]