Search code examples
c++stringvector

Shows no error but also doesnt give any output


I am trying to take two strings as input and combine them and all their individual character into a vector.

Full Code:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str1;
    string str2;

    cin>>str1>>str2;

    vector<char>vec;

    for(int i=0;i<str1.length();i++){
        vec[i]=str1[i];
    }

    int k=str1.length();
    for(int i=0;i<str2.length();i++){
        vec[k]=str2[i];
        k++;
    }
    
    for(int i=0;i<vec.size();i++){
        cout<<vec[i];
    }
}

What am I missing? Am I missing a concept about strings here?

I am trying to take two strings as input and combine them and all their individual character into a vector.

In terminal code shows no error, takes input for both strings, but shows no output.


Solution

  • You declare a vector of chars vec with no initial size. At this point, vec has a size of 0, meaning that it can't store any elements (without getting into too much detail). Then, you attempt to modify the vector with vec[i]=str1[i]. Since vec doesn't actually have any storage to store the elements, you're modifying memory you don't own. This is a segmentation fault, and kills the program. When a segmentation fault occurs, there is no output produced, hence why there isn't output.

    You should allocate memory for vec using the method resize:

    //...
    vector<char> vec;
    vec.resize(str1.length() + str2.length());
    
    for (int i = 0; i < str1.length(); i++) {
    //...
    

    There shouldn't be a segmentation fault after this.