Q:

C++ Strings | Find output programs | Set 1

belongs to collection: C++ find output programs

0

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

string 1-string 2

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:

string 1-string 2

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:

main.cpp: In function ‘int main()’:
main.cpp:11:13: error: invalid operands of types ‘char [9]’ 
and ‘const char [2]’ to binary ‘operator+’
     s3 = s1 + "-" + s2;
          ~~~^~~~~

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

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Strings | Find output programs | Set 2... >>
<< C++ Arrays | Find output programs | Set 5...