0

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

2
  • c is an empty string. If you want to add to it, use c += s[i]; You also do not need to null terminate it, and you would be better off using s.size() to know how long to iterate, or a range based for loop. Commented Aug 8, 2018 at 3:55
  • Off-topic, but what is "strings.h", and you should avoid using bits/stdc++, and instead just include what you need. Commented Aug 8, 2018 at 4:21

1 Answer 1

1
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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.