Search code examples
c++operator-overloadingstring-concatenation

Concatenating 2 string in c++ using operator overloading


I'm trying to concatenate 2 strings. One of the string is defined whereas the other string's length is not fixed. Whenever I input the second string as suppose 'to my world', it does not print the entire string on concatenation. I'm new to programming, so please help me out.

#include <iostream>
using namespace std;

int main() {
    string s = "Welcome";
    string t="",k;
    cin>>t;
    k=s+t;
    cout<<k;
return 0; }

Solution

  • Use std::getline instead of the operator >> that allows to enter only one word delimited by a white-space character. For example

    #include <iostream>
    #include <string>
    
    int main() 
    {
        std::string s = "Welcome";
        std::string t, k;
    
        std::getline( std::cin, t );
        k = s + ' ' + t;
    
        std::cout << k << std::endl;
    
        return 0;
    }