2012-05-25 60 views
0

的代碼是複製和利用圖書館functions.the碼,我用串聯字符串widout:如何在字符串連接的輸出中清除不必要的符號?

#include<stdio.h> 
#include<conio.h> 
#include<string.h> 
#define MAX 100 
char* newStrCpy(char string1[],char string2[]) 
{ 
     int i=0; 
     while(string1[i]!='\0') 
     { 
      string2[i]=string1[i]; 
      i++; 
     } 
return (string2); 
} 
char* newStrCat(char destination[],char arr[]) 
{ 
int a=0; 
int destlen=0; 
while(destination[destlen]!='\0') 
{ 
    destlen ++; 
} 
while(a<(MAX-destlen)) 
{ 
    destination[(destlen+a)]=arr[a]; 
    a++; 
} 
return destination; 
} 
void main() 
{ 
char string1[MAX],string2[MAX]; 
int i=0,j=0; 
char bak[5]="\n is"; 
char som[50]=" the concatenated array."; 
fflush(stdin); 

printf("Enter a string:\n"); 
scanf("%[^\n]s",&string1); 
newStrCpy(string1,string2); 
printf("The copied string is:\n"); 
while(string2[i]!='\0') 
{ 
    printf("%c",string2[i]); 
    i++; 
} 
newStrCat(string2,bak); 
newStrCat(string2,som); 
printf("\nThe conctenated string is:\n"); 
while(string2[j]!='\0') 
{ 
    printf("%c",string2[j]); 
    j++; 
} 
fflush(stdout); 
getch(); 
} 

和輸出我得到:

Enter a string: 
Welcome!! 

複製的字符串是:

Welcome!! 
he concatenated string is: 
Welcome!! 
is the concatenated string 
+0

你應該終止你所有的字符串。 – vanza

回答

0

需要初始化你string2陣列:

char string2[MAX] ={'\0'}; 

這確保所有成員都設置爲\0 [參考#1],你不必費心手動附加一個\0複製後到你的字符串數組。
當前,您的string2數組永遠不會空終止,因此while循環會一直持續到它遇到\0,並且它輸出的垃圾不是字符串的一部分。

同樣在一個側面說明,

fflush(stdin); 

使你的程序有未定義行爲的野獸,不使用它。
fflush()保證在輸出流stdout上工作。


[參考#1]
C99標準6.7.8.21

如果在一個大括號內的列表更少初始化值多於一個聚合的元件或部件,或用於初始化一個已知大小的數組的字符串字符數比字符串數組中的元素少,則聚合的其餘部分應隱式地初始化爲與具有靜態存儲持續時間的對象相同。

0

請確保您複製了newStrCpy/Cat中的空終止符(字符串的最後一個字符)。

+0

謝謝大家。它被解決了。我用fflush。 –