Strings

I'm getting an odd result. What I'm trying to do is the following. I want to write what ever was entered into the constructor as an int, convert that to a string, then combine that string with the equation string.

equation = num/equation;

If 5 was input into the object Rational A(5);I want it to eventually be added to my string so that my string that once read, "0/1" will now read, "5/1".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Code I'm attempting to convert two strings into one string
char *Rational::combineString(std::string a, std::string b){
	//Converting Strings to char array
	char *strA = new char [a.length() + 1];
	char *strB = new char [b.length() + 1];
	
    size_t len1 = strlen(strA);
    size_t len2 = strlen(strB);
    char *result = new char (len1+len2+1);

    memcpy(result, strA, len1);
    memcpy(result+len1, strB, len2+1);
    return result;
}

//Constructor that accepts 1 int
  Rational::Rational(int num){
	std::cout << "Inside the constructor that accepts 1 int"<< std::endl;
	std::string temp;

	numerator = num;
	denominator = 1;
	equation = "0/1";
	temp = convertInt(num);
	equation = combineString(temp, equation);

	std::cout << numerator << "/" << denominator << std::endl;
	std::cout << equation << std::endl;
}


I'm in a little over my head. If you could provide an answer in as simple as terms as possible, I would appreciate it. Thanks.

Here is what I believe each line of the CombineString function is doing.
Line 2: Function is going to return Char pointer, and accepts two strings for input

Line 4: Creating a char pointer strA that points to a dynamically allocated char that is a.lenght() + 1 in size.

Line 5: Creating a char pointer StrB that points to a dynamically allocated char that is b.lenght() + 1 in size.

Line 7 & 8: Don't totally understand what is going on. Looks like its storing the size of strA and StrB into len1 and len2 respectively.

Line 9: Creating a new char pointer that is the size of both original strings +1.

Line 11: memcpy is copying StrA into result, len1 being the size of StrA.

Line 12: memcpy is copying StrB into result+len1 (moving up the elements until you go to an empty space), then len2+1 lists the string size and adds 1 for null terminator.

Line 14: returns result which is the starting address of the result array.
I found the solution on my own. Ignore the above question. I ended up deleting the combineString(), all I had to do was concatenate two strings.

(See line 8)
1
2
3
4
5
6
7
8
9
10
11
12
13
Rational::Rational(int num){
	std::cout << "Inside the constructor that accepts 1 int"<< std::endl;
	std::string temp;
	
	numerator = num;
	denominator = 1;
	temp = convertInt(num); // converts the int num to string and stores in temp
	equation = temp + "/1";
	simplifyInt();

	std::cout << numerator << "/" << denominator << std::endl;
	std::cout << equation << std::endl;
}
Last edited on
Topic archived. No new replies allowed.