-4

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.

Algirdas Preidžius
  • 1,769
  • 3
  • 14
  • 17

4 Answers4

3
s2[j]=s1[i];

s2 is initially empty. Accessing s2[j] is out of bounds and undefined behavior.

Change it to s2+=s1[i] and all is good.


Update FYI, in mordern C++ you don't usually need to deal with lengths because you should prefer using standard library algorithms:

#include<iostream>
#include<string>
#include<algorithm>

int main()
{
    std::string s1,s2;
    getline(std::cin,s1);
    std::copy_if(s1.begin(), s1.end(), std::back_inserter(s2), [](char ch){
        return ch!=' ';
    });
    std::cout<<s2.length();
    std::cout<<s2<<'\n';
}
Max Langhof
  • 23,383
  • 5
  • 39
  • 72
balki
  • 26,394
  • 30
  • 105
  • 151
2

The length of a default-constructed string is 0.

s2[j] accesses the character at the index j. If that character doesn't exist, then the behaviour of the program is undefined.

When the length of the string is 0, for any j greater than 0, s2[j] has undefined behaviour, because that character doesn't exist. s2[0] is well defined and refers to the null terminator.

You may have intended to add characters to the string. You can add characters to a string for example using the push_back member function or += operator.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

You cannot use [] to increase the s2 string size. If you use resize to grow it beforehand, it should work:

        s2.resize(j+1);
        s2[j]=s1[i];
        j++;

push_back() of a character on a std::string would do the same. However, I offer you this answer as it keeps the character assignment you already had. Philosophy of minimal answer/change :-).

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
-1
#include<iostream>
using namespace std;
int main()
{
    string s1,s2;
    int i,l1;
    getline(cin,s1);
    l1=s1.length();
    for(i=0;i<l1;i++)
    {
        if(s1[i]!=' ')
        {
            s2.push_back(s1[i]); //CHANGE MADE HERE
        }
    }
    cout<<s2.length();
    cout<<s2<<endl;
} 

As @iBug mentioned you can also use push_back as shown above

jim
  • 1,026
  • 2
  • 15
  • 37