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
cis an empty string. If you want to add to it, usec += s[i];You also do not need to null terminate it, and you would be better off usings.size()to know how long to iterate, or a range based for loop.