简体   繁体   中英

how can i concatenate determined number of characters with another string?

I'm new to programming and I'm trying to make a function that can concatenate determined number of characters to another string. It's counting the number of characters correctly but it wont display like the task wants. Anyone could explain me why?

An example would be (expected output):

String 1: Testing

String 2: String

N: 4 (Value is asked for the user)

Result: TestingStri

My code so far is this:

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
void ConcatenateString(char *string, char *string2); 
int main() 
{ 

   char string[100]; 
   char string2[100]; 

   ConcatenateString(string, string2);
   DisplayStrings(string, string2); 

} 
void ConcatenateString(char *string, char *string2)
{
    int N;
    system("cls");
    printf ("First string: ");
    gets(string);
    fflush(stdin);
    printf ("Second string: ");
    gets(string2);
    printf("Number of characters: ");
    scanf ("%d", &N);

    int i;
    int count = 0;
    for(i=0;string2[i];i++)
    {
        count++;
    }

    while (count < N)
    {
        string2[count++] = string2[i];
    }   
    strcat(string,string2); 
}
void DisplayStrings(char *string, char *string2)
{
    printf("\nFirst String:\n");
    printf("%s\n", string);
    printf("\nSecond String:\n");
    printf("%s\n", string2);

}

The wrong (actual) output:

String 1: Testing
String 2: String
N: 4
Output: TestingString

It's not really displaying 4 characters from string 2 (for example) that I ask for.

for(i=0;string2[i];i++)
{
    count++;
}

This code counts the number of bytes in string2 . I think you want string here instead.


while (count < N)
{
    string2[count++] = string2[i];
}   

This code copies stuff in string2 from one place to the other. I think you want to copy from string2 to string instead.


strcat(string,string2); 

This code concatenates string and string2 . You definitely don't need this; it will only confuse you when you display the result.

Which book are you reading?

The pervasive errors you have are common for the populous who don't read books . That is to say, from my observations, those who read books don't have these kinds of problems...

  • system("cls"); makes no sense when you learn from a nice book, as it defeats the purpose of the lesson it should teach: use the most appropriate tool for the job, and if you want to clear the screen that tool is a user interface other than the console . Don't clear consoles, and certainly don't use cls to do so.
  • Older books are still using gets , but that has been deprecated. Consider using fgets instead.
  • You should never fflush(stdin) . On that note, you should probably fflush(stdout) when you're writing data that doesn't end with '\\n' to stdout .
  • int n = scanf(...); make sure you check n ... and don't just guess ; read the manual .
 int i; int count = 0; for(i=0;string2[i];i++) { count++; } 

Since count and i both increment synchronously and start at 0 , they'll both be equal to strlen(string2) here. You should just write count = strlen(string2); ... on that note, these variables should be size_t , rather than int .


 while (count < N) { string2[count++] = string2[i]; } 

This is undefined behaviour, at least for values of N that are larger than string2 . It's essentially memset(string2 + count, '\\0', N - count) ; that is to say, all you are doing here is zeroing the bytes at the end of the array. You don't need this code. Get rid of it. Burn it in fire!


fgets(string, sizeof string, stdin);
fgets(string2, sizeof string2, stdin);
 strcat(string,string2); 

Ahh, why didn't you do that in the first place? Don't forget to remove the newline characters...

As others have told you, never use gets() as it is infamous for its security issues. Read this .

Use fgets() like

char str[100];
fgets(str, 100, stdin);

You may check the value returned by fgets() to see if all went well. NULL is returned on error.

fgets() will read in the trailing \\n as well. You may remove it like

size_t l=strlen(str);
if(str[l-1]=='\n')
{
    str[l-1]='\0';
}

to replace the \\n with \\0 denoting end of string.


To concatenate n characters of a string str2 to str1 (assuming that str1 has enough space. Checks against overflow must be in place when you do this), you could do

sprintf(str1, "%s%.*s", str1, n, str2);

The value of n will stand in for the * in the format string. So if n is 4 , it will be %.4s which means the first 4 characters from the corresponding string.

Before doing this, check if str1 has enough space with something like

if(strlen(str1)+n+1 < 100)// where 100 is the size of the character array str1
{
    sprintf(......);//the sprintf() call
}

See this post to see why fflush(stdin) is not considered good.

And this to see why the use of system() is better avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM