strcat()函數常見問題


  strcat(char *_Destination,const char *_Source)函數的功能是將后一個字符串粘貼到前一個字符串的末尾

原型

  char *strcat(char *_Destination,const char *_Source)

常見錯誤

  strcat函數常見的錯誤就是數組越界,即兩個字符串連接后,長度超過第一個字符串數組定義的長度,導致越界

example1:
 1 void charWrite() {
 2     FILE *file;
 3     char type[4] = "wt+";
 4     char path[30] = "C:/Users/Fahy/Desktop/";  //數組總長度為30個字符,初始化存入22個字符
 5     char filename[20],ch;
 6     scanf("%s", filename);    //如果超過8個字符,strcat將兩個字符串結合時,就會越界
 7     ch = getchar();
 8     ch = getchar();
 9     strcat(path, filename);
10     if (!(file = fopen(path, type))) {
11         printf("Can't open this file \"%s\"", path);
12         system("pause");
13     }
14     else {
15         while (ch != EOF)
16         {
17             fputc(ch, file);
18             ch = getchar();
19         }
20     }
21     fclose(file);
22 }

解決方法

  別無他法,只能將第一個參數定義長點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM