I made a program in C++ to take a sentence as input and wanted display the sentence after omitting the spaces , however I'm getting weird results ... s2 is the string containing the sentence after omitting spaces. I can access the string s2 as s2[i] , but I'm getting no output when I try cout<< s2; and value of s2.length() gets printed as 0 ??
#include<iostream>
using namespace std;
int main()
{
string s1,s2;
int i,j,l1,l2;
getline(cin,s1);
l1=s1.length();
j=0;
for(i=0;i<l1;i++)
{
if(s1[i]!=' ')
{
s2[j]=s1[i];
j++;
}
}
cout<<s2.length();
cout<<s2<<endl;
}
Expected : s2.length() shouldn't be 0 and cout<< s2; should work.