Writing a c program to attach a prefix to a list of strings entered

帅比萌擦擦* 提交于 2020-01-16 14:08:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!