【发布时间】:2018-03-16 13:04:00
【问题描述】:
#include <stdio.h>
#include <string.h>
void mergeStr(char *a, char *b, char *c);
int main()
{
char a[80],b[80];
char c[80];
printf("Enter the first string: \n");
gets(a);
printf("Enter the second string: \n");
gets(b);
mergeStr(a,b,c);
printf("mergeStr(): ");
puts(c);
return 0;
}
void mergeStr(char *a, char *b, char *c)
{
int size; int i ; int j=0 ; // again, forgot to initialize j
char ch;
char temp[80] ;
/* Merge string a and string b together, then sort them alphabetically */
c = strcat(a,b) ;
size = strlen(c) ;
for (ch = 'A' ; ch <= 'z' ; ch++ ) { // iterates from A-Z and a-z
for (i=0 ; i<size ; i++) { // which for loop comes first is important, in this case since we want duplicates we should allow i to iterate everything for every case of ch
if (c[i] == ch){
temp[j] = c[i] ;
j++ ;
}
}
}
for (i=0 ; i<size ; i++) {
c[i] = temp[i] ; // assign sorted string back to c
c[size] = '\0' ;
}
// puts(c) <- when puts() is run here, desired output is given
}
在这个程序中,函数接受 char a ,将它与分配给 c 的 char b 连接起来。
char c 然后通过 puts(c) 在 main 函数中排序并打印出来。
例如,
Enter the first string:
afkm
Enter the second string:
bbbggg
abbbfgggkm
mergeStr():
这是从 void mergeStr() 函数中运行 puts(c) 时得到的输出。
但是,int main() 中的 puts(c) 不打印任何内容。
【问题讨论】:
-
不要使用
gets(),这是一个废弃的旧危险函数。
标签: c