This section contains the C++ find output programs with their explanations on C++ Strings (set 1).
Program 1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "string 1";
string s2 = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Program 2:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "string 1";
char s2[] = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Program 3:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char s1[] = "string 1";
char s2[] = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Answer Program 1:
Output:
Explanation:
Here, we used string class, which is present in <string> header file. We created three objects s1, s2, and s3. s1 and s2 initialized with "string1 " and "string 2" respectively. Here '+' operator is overloaded to concatenate strings. Here we concatenate s1, "-", and s2 using '+' operator and assigned the final string to the s3 object, and then we print s3 on the console screen.
Answer Program 2:
Output:
Explanation:
Here, we used string class, which is present in <string> header file. We created two objects s1 and s3. Here s2 is the character array. s1 and s2 initialized with "string1 " and "string 2" respectively. Here '+' operator is overloaded to concatenate strings as well as the character array. Here we concatenate s1, "-", and s2 using '+' operator and assigned the final string to the s3 object, and then we print s3 on the console screen.
Answer Program 3:
Output:
Explanation:
Here, we are trying to concatenate two character arrays using '+' operator. But '+' operator cannot concatenate two characters array. If we used any one of string object then '+' operator can be used for concatenation. That's why the above program will generate a compilation array.
need an explanation for this answer? contact us directly to get an explanation for this answer