Archive for Programming

strcat犯了个简单的错误

char * s="customer.tbl";

strcat(s,”n”);

这样会出问题,为什么呢?


  #include <string.h>
  char *strcat( char *str1, const char *str2 );

The strcat() function concatenates str2 onto the end of str1, and returns str1. For example:

   printf( "Enter your name: " );   scanf( "%s", name );   title = strcat( name, " the Great" );   printf( "Hello, %sn", title );            

str1应该是一个可修改的char数组区域。
可以这样写


char s0[32]="";

char * s="customer.tbl";
strcat(strcat(s0,s),"n");

许久没写程序了,这样简单的错误也犯。
而对于string,

string s="customer.tbl"+"n";

同样也是不允许的。
因为string允许的操作


string operator+(const string& s1, const string& s2 );

string operator+(const char* s, const string& s2 );

string operator+( char c, const string& s2 );

string operator+( const string& s1, const char* s );

string operator+( const string& s1, char c );

变通的办法是


string s="customer.tbl";

s=s+"n";


Del.icio.us : , ,

Leave a Comment