【发布时间】:2020-04-14 23:35:07
【问题描述】:
我正在练习学习 C 并创建程序,其中用户输入一个 int,然后输入多个名字和姓氏。然后程序将打印所有名字姓氏名字。我试图在以前的帖子中找到这个问题,例如this,但找不到我的问题的好答案。 例如,
输入:
2
杰克·琼斯
米拉咕
输出:
琼斯·杰克
古米拉
相反,我的程序会打印出行话:
����4LJo �5Lne Jack
去迈拉
下面是我的代码:
#include <stdio.h>
#include <string.h>
int main(void) {
//! word1 = showArray(word1, cursors=[i], width=0.5)
//! word2 = showArray(word2, cursors=[i], width=0.5)
int num;
//char word2[8];
int count = 0;
char first[101];
char last[101];
char all[1000];
int last_letter_of_all;
scanf("%i", &num);
while(count != num){
scanf("%s %s", first, last);
int len_first = strlen(first);
int len_last = strlen(last);
//printf("%i %i\n", len_first, len_last);
//add letters of last
for(int k = 0; k < len_last; k++)
{
last_letter_of_all = strlen(all);
char c = last[k];
all[last_letter_of_all] = c;
// printf("%c\n", c);
}
//find last location of last name added
all[last_letter_of_all] = ' ';
//add first name
for(int l = 0; l < len_first; l++)
{
last_letter_of_all = strlen(all);
char c = first[l];
all[last_letter_of_all] = c;
}
//find last space of location
all[last_letter_of_all+1] = '.';
count++;
}
for(int i = 0; i < strlen(all); i++)
{
if(all[i] != '.')
{
printf("%c", all[i]);
}
else
{
printf("\n");
}
}
return 0;
}
我已经为此苦苦挣扎了一段时间。我来自 Java,对 C 很陌生,但我相信这可能与表示数组结束的“/0”有关。
【问题讨论】:
-
请注意,当您第一次调用
strlen(all)时,all是未初始化的。