我做了一個程序,它接收2到5個字符串,並使用可變參數函數連接在一起。使用可變參數函數連接字符串
到目前爲止程序工作正常,但它總是在顯示完整的字符串之前顯示3個隨機字符。
例如:
Please insert number of strings: 3
string 1: car
string 2: bike
string 3: plane
完全字符串:
=$>carbikeplane
我作了一些調整,以程序試圖找到原因並修復它,但我總是得到相同的結果。
完整的程序如下所示。 有關該計劃的幾點意見:
- 我打印在程序的不同部分的琴絃,因爲我試圖找出哪裏出了問題來了。所以一些printf()函數可能沒有意義。
- 主要功能似乎很好,問題出在稍後定義的功能上。
注意:我還在學習C語言,所以可能會有一些代碼可能/可能會創建未定義的行爲,如果有的話,我會很感激,如果您能指出這些。
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
char *function(int num, ...);
int main(void)
{
char line1[80] = " ", line2[80] = " ", line3[80] = " ", line4[80] = " ", line5[80] = " ";
int count = 0, count2;
char *newStr;
int i;
int status;
do {
fflush(stdin);
printf("\nPlease select the number of strings (max. 5): ");
scanf("%d", &count);
}while(count < 2 && count > 5);
count2 = count;
fflush(stdin);
status = 1;
for(i = 1 ; count > 0; count--, i++)
{
switch(status)
{
case 1:
{
printf("\nInput string[%d]: ", i);
gets(line1);
status = 2;
break;
}
case 2:
{
printf("\nInput string[%d]: ", i);
gets(line2);
status = 3;
break;
}
case 3:
{
printf("\nInput string[%d]: ", i);
gets(line3);
status = 4;
break;
}
case 4:
{
printf("\nInput string[%d]: ", i);
gets(line4);
status = 5;
break;
}
case 5:
{
printf("\nInput string[%d]: ", i);
gets(line5);
status = 6;
break;
}
}
}
printf("\n%s\n%s\n%s\n%s\n%s\n", line1, line2, line3, line4, line5);
/*call the function of variable arguments*/
/*memory allocation of newstr*/
newStr = (char *)malloc(420*sizeof(char) +1);
switch(count2)
{
case 2:
{
newStr = function(2, line1, line2);
break;
}
case 3:
{
newStr = function(3, line1, line2, line3);
break;
}
case 4:
{
newStr = function(4, line1, line2, line3, line4);
break;
}
case 5:
{
newStr = function(5, line1, line2, line3, line4, line5);
}
}
printf("\nThe final string is: \n");
printf("%s", newStr);
return 0;
}
char *function(int num, ...)
{
va_list arg_ptr;
int b;
char *string;
char *curstr;
va_start(arg_ptr, num); /*initialize the arg_ptr*/
string = (char *)malloc(420*sizeof(char) + 1);
*string = " ";
for(b=0; b < num; b++)
{
curstr = va_arg(arg_ptr, char *);
string = strcat(string,curstr);
}
printf("\n%s", string);
va_end(arg_ptr);
return string;
}
你用什麼編譯器簡單地完成,結束輸入時按
ctrl+d
? '* string =「」;'無效並且不應該編譯... – fritzone 2014-09-10 08:18:41每日提醒不要投入'malloc()'的返回值。 – Igor 2014-09-10 08:20:10
要完成@Igor語句,我建議你閱讀這個問題,因爲我認爲這是一個有趣的事情要了解:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of- malloc – Logar 2014-09-10 08:22:52