+ 1

C++ string operations behave strange

Why str4 here give me like that result? https://code.sololearn.com/cFD8d8Jui7fZ/?ref=app

6th May 2022, 6:40 PM
Mustafa Emad
Mustafa Emad - avatar
7 Answers
+ 1
Yes. so There is no need to use str3, str4. They works as dublicates.. You're welcome..
6th May 2022, 8:30 PM
Jayakrishna 🇮🇳
+ 2
//hope it helps.. Read comments.. Mustafa Emad #include <iostream> using namespace std; int main() { string str1, str2; getline(cin, str1); // first getline(cin, str2); //second string str3 = str1.append(" " + str2); // apends " "+str2 to str1 and returns new str1 // so now str1= "first second" //str3 = "first second" //str2 = "second" cout << str3.length() << endl << str3 << endl; str1.swap(str2); //swaps str1,str2 so then str1= "second" , str2="first second" string str4 = str1.append(" " + str2); //appends str2 ("first second") to str1("second") and then returns new str1 //so now str1="second first second" //str4 = "second first second" //str2 = "first second" cout << str4.length() << endl << str4 << endl; return 0; }
6th May 2022, 8:13 PM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 so append didn't affect on variable only but all the coming code that's help thanks I got it
6th May 2022, 8:24 PM
Mustafa Emad
Mustafa Emad - avatar
0
What result? What strange you found? can you detail it!!!
6th May 2022, 7:23 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 make additional text at second append
6th May 2022, 7:40 PM
Mustafa Emad
Mustafa Emad - avatar
0
Mustafa Emad I run it and all fine. Add your try with input and output and expected output.. So I can understand your doubt..!
6th May 2022, 7:44 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 the code is expected that: first second second first but output is: first second second first second
6th May 2022, 8:00 PM
Mustafa Emad
Mustafa Emad - avatar