I am trying to write a program that erase trailing and front spaces
of a string.
The code I came up with does something weird instead,
it repeats the input several times and in some instances,
it is pushed so far to the left that part of the inputted word
disappears.
I am not sure what makes it do such a thing.
it repeats the input several times and in some instances,
it is pushed so far to the left that part of the inputted word
disappears.
You're printing the string after removing each space. Move line 33 to line 35 to print it just once when you're done processing it.
At that point you're probably find that you're removing spaces from the middle as well as the beginning and end. You will also find that you fail to remove two spaces in a row.
I am not sure I am following you.
All I need to know is where exactly my mistake is.
I think the point that lastchance was making is that your algorithm is flawed (for the reasons I mention above). He's showing you an algorithm that will work.
The code that Duthomhas links to will work, but if this is an assignment, you should try to write it yourself instead using lastchance's suggestion or ne555's.
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter the string ";
getline(cin,str);
int len=str.length();
char newstr[len];
//Removing one or more blank spaces from string
int i=0,j=0;
while(str[i]!='\0')
{
while(str[i] == ' ')//using loop to remove consecutive blanks
i++;
newstr[j]=str[i]; //newstr[j++]=str[i++] we can also use this instead
i++;
j++;
}
newstr[len-1]='\0';//terminating newstr, we use -1, as j was a post increment.
cout<<"\n String after removal of blank spaces is:"<<newstr;
return 0;
}