a.utfull.day
a.utfull.day

Reputation: 110

Unable to assign string to string data type in c++

I'm trying to write a simple program to which takes away the spaces from a string as follows:

#include <iostream>
#include <bits/stdc++.h>
#include <strings.h>
#include <string>
using namespace std;

int main()
{
    string s;
    getline(cin,s);
    cout<< s;
    string c;
    int i =0,j=0;
    while(s[i]!='\0'){
        if(s[i] == ' ')
            i++;
        else{
            c[j] = s[i];
            j++;
            i++;
        }
    }
    c[j] ='\0';
    cout << c; //unable to print

 }   

Here when I try to print c I can't seem to be able to get a result. When I used c as a character array it worked but I'd still like to know what I was doing wrong. Thanks so much

Upvotes: 0

Views: 164

Answers (1)

R Sahu
R Sahu

Reputation: 206577

string c;

creates an empty string. After that,

c[j] = s[i];

is cause for undefined behavior.

You can solve the problem using many strategies. Here are a couple of them:

Construct c with large enough size

string c(s.size(), '\0');

Use std::string::push_back

Instead of

    c[j] = s[i];

    ...

c[j] ='\0';

use

    c.push_back(s[i]);

    ...

c.push_back('\0');

Upvotes: 1

Related Questions