C primer plus 第六版 第十一章 第七題 程式設計練習答案
阿新 • • 發佈:2018-12-28
Github地址: φ(>ω<*)這裡這裡。
/*
本次任務是設計一個strncpy(s1,s2,n)這樣的函式,名字為 mystrncpy。
目標字串不能以空字元結尾,如果第二個引數的長度大於n.原函式如果大於n是不會把s1結尾程式設計空函式的。
*/
#include<stdio.h> #define n 20 char *mystrncpy(char * s1, const char * s2, int o); int main(void) { char s1[n+n] = {}; char s2[n+n] = {}; char quit = 0; while(quit != 'q') { printf("Please input the first string(The limit is 20 character):\n"); fgets(s1, n, stdin); fflush(stdin); printf("Please input the second string(The limit is 20 character):\n"); fgets(s2, n, stdin); fflush(stdin); mystrncpy(s1, s2, n-1); printf("The result with copy is like this:\n"); fputs(s1, stdout); printf("Do you want to quit or continue(Enter 'q' to quit)? Choies:\n"); fflush(stdin); quit = getchar(); } printf("Bye ~\n"); getchar(); return 0; } char *mystrncpy(char * s1, const char * s2, int o) { // 我是沒見過原strncpy的函式內部具體實現。 // 這裡要完成相應操作,我的思路是: // 迴圈處理,測試條件就是讀入字元小於n, 和讀到s2的結尾 // 這樣就保證了不溢位,也保證了讀入的終點。 int i = 0; // 不過在那樣處理之前,我得先找到s1的結尾。 // 雖然可以用strlen,但是既然不能用 strncpy, 那我就不用string.h標頭檔案!!!! while( *s1 != '\n' && *s1 != '\0' ) { // 這裡選用換行符是因為 main() 中我用 fgets()函式獲取輸入了。該函式會保留結尾的換行符。 // 如果溢位了還會有空字元。。 s1++; } while( i < o && *s2 != '\0') { *s1 = *s2; s1++; s2++; } return NULL; }