问题
I'm kind of new to C programming and I'm writing a program to attach a prefix to a list of strings entered by a user. here's a snippet of code.
char names[5][20], prefix[5];
int i=0;
// accept 5 names and a prefix
printf("Please enter the 5 names and a prefix\n");
for(i;i<=4;i++ )
{
printf("Enter name %d\n ",i+1);
scanf("%s", &names[i]);
}
printf("prefix: \n ");
scanf("%s", &prefix);
printf("\n\n\n");
for(i=0;i<=4;i++)
{
strcat(prefix,names[i]);
printf("%s\n", prefix);
}
My problem is that instead of adding the prefix to the next string entered it's just listing them all.
Here's what I mean:
Please enter the 5 names and a prefix
Enter name 1
i
Enter name 2
c
Enter name 3
h
Enter name 4
a
Enter name 5
e
prefix:
m
mi
mic
mich
micha
michae
回答1:
The array prefix has five elements. The sub-arrays in names have 20 elements.
Even if each string is only one character long, that will be a string of six character (not including the string zero terminator, which makes it seven). That will not fit into an array of five characters.
You need to increase the length of prefix by quite a bit.
It is also not doing what you want, since that's not how strcat work.
If you just want to print the strings with the prefix, then do that:
printf("%s%s\n", prefix, names[i]);
If you want to actually add a prefix to a string for later usage, then I suggest using a second array for the prefixed strings:
char prefixed_names[5][25];
for (size_t i = 0; i < 5; ++i)
{
strcpy(prefixed_names[i], prefix); // Copy the prefix to the new string
strcat(prefixed_names[i], names[i]); // Append the name
}
回答2:
If I understand what you would achieve:
char names[5][20], prefix[5];
char tmp[32];
int i=0;
// accept 5 names and a prefix
printf("Please enter the 5 names and a prefix\n");
for(i;i<=4;i++)
{
printf("Enter name %d\n ",i+1);
scanf("%s", &names[i]);
}
printf("prefix: \n ");
scanf("%s", &prefix);
printf("\n\n\n");
for(i=0;i<=4;i++)
{
strcpy(tmp, prefix);
strcat(tmp, names[i]);
printf("%s\n", tmp);
}
The problem is that you are concatenating all the string in the same container prefix.
来源:https://stackoverflow.com/questions/48928606/writing-a-c-program-to-attach-a-prefix-to-a-list-of-strings-entered