سؤال

The question requires combining two strings(the longer string in the front and the shorter one after the longer one) without using <string> header file.Each string inputted can't exceed 20 characters. My logic behind this is:

  1. first use strlen to get the length of the str1 and str2,
  2. use str3 to store the longer string, and str4 to store the shorter.
  3. add str3 and str4 to str5

Here is my code:

#include<iostream>
using namespace std;

int main()
{
    // combine two strings , longer in the front, and shorter 
    // after it. do not use strcat
    char str1[20],str2[20],str3[20],str4[20],str5[40];
    // str1 and str2 stores original data, str3 stores longer 
    // and str4 stores shorter, str5 stores total
    int j=0;
    cin.getline(str1,20);
    cin.getline(str2,20);
    if(strlen(str1)<=strlen(str2))
    // give longer string value to str3,shorter to str2
    {
        for (int i=0;i<20;i++)
        {
            str3[i]=str2[i];
            str4[i]=str1[i];
        }
    }
    else
    {
        for (int i=0;i<20;i++)
        {
            str3[i]=str1[i];
            str4[i]=str2[i];
        }
    }
    for(j=0;str3[j]!='\0';j++)
    {
        str5[j]=str3[j];
    }
    for(int i=j;i<40;i++)
    for(int m=0;m<20;m++)
    {
        str5[i]=str4[m];
    }
    cout<<str5<<endl;
    return 0;
}

Here is the ouput:

enter image description here

What's my problem here? What are those characters in between the two strings? Thank you!!

هل كانت مفيدة؟

المحلول 2

Everything is fine (!) up to this point

for(int i=j;i<40;i++)
for(int m=0;m<20;m++) // This loop runs m=0 to 20 for each position of i
{
    str5[i]=str4[m];
}

For each index i you are copying in all 20 elements from str4, leaving just the value at str4[19] which could be anything

Just increment i and m by one together

int m = 0;
for(int i=j;i<40;i++)
{
    str5[i]=str4[m++];
}

نصائح أخرى

Especially since you explicitly mentioned being a beginner, the solution is to use std::string:

#include <iostream>
#include <string>

int main() {
    std::string a;
    getline(std::cin, a);

    std::string b;
    getline(std::cin, b);

    // Ensure that the longer string goes to the front.
    if (a.size() < b.size());
        swap(a, b);

    std::string result = a + b;

    std::cout << result << '\n';

    // Or, simply:
    std::cout << a << b << '\n';
}

The message here is that C++, despite its quirks, is a very high level language if you rely on its library instead of implementing every low level operation from scratch.

You are copying the entire 20 characters, 40 characters in the loop into the variables. stop copying when you find a '\0' character.

But using the std::string will make life simpler :)

Using std::string is nice and all but here's a few tips for working with char*:

1) You shouldn't copy strings to separate shorter and longer string, just use pointers and then work with these pointers, something along these lines:

const char *longer_string = 0, *shorter_string = 0;
if(strlen(str1)<=strlen(str2))
   {
     shorter_string = str1;
     longer_string = str2;
   }
 else
   {
     shorter_string = str2;
     storter_string = str1;
   }

2) Using strcpy and strcat to combine strings could make life a lot easier:

    char *combined_string = new char [strlen (shorter_string) + strlen (longer_string) + 1];
    strcpy (combined_string, longer_string);
    strcat (combined_string, shorter_string);

Some compilers would say that these functions aren't safe and you have to stick to _s versions, but I guess it's entirely up to you.

Since this is obviously homework: I'll just point out the existence of the function strcat, and the fact that you can use char* to the arrays, and just swap them, without having to recopy anything between the initial read and the concatenation (which means that you only need two arrays: one for each of the inputs, and one for the final value).

And also, when calculating sizes, etc. do not forget that C style strings have an extra '\0' at the end, and make allowances for it.

As @David Sykes has pointed out, the problem is with your for loop. So when you read input from cin ,it is not necessary that your input string contains 20 character. But in you form loop you are looping through those string beyond their length which may contains garbage characters. Example

char str1[20]
 cin.getline(str1,20);
 cout << str1[19] << endl;

Suppose your input for above code is "ABCD" which contains only 4 characters but your array has capacity of 20. So the remaining space has junk characters and when you will try to print any thing beyond actual length you will get wild character as you are getting in your code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top