I wrote a program which is supposed to remove excess spaces from a string. But it only shows characters before spaces. It finds a space and checks the character after that whether it is a space. Depending on excess spaces it shifts other characters over excess spaces. But output is very confusing.
input: "qwe(2 spaces)rt(one space)y"
output: "qwe(one space)rt(one space)y"
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string a;
cin >> a;
int len = a.length();
int new_len=len;
int z,s=0;
for(int i=0; i<new_len; i++){
if(a[i]==' '){
z=i+1;
s=0;
//Assigning the number of excess spaces to s.
while(a[z]==' '){
s++;
z++;
}
//doing the shifting here.
if(s>0){
for(int l=i+1; l<new_len-s; l++){
a[l]=a[s+l];
}
}
new_len-=s;
}
}
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
find_first_of()andfind_first_not_of()and their simulars.std::string a; cin >> a;skips leading whitespace and only reads data intoauntil it hits more whitespace (which isn't read intoa) or end-of-file, so you can't possibly have input with any whitespace to strip. If you'd putcout << "a '" << a << "'\n";into your program you'd have noticed: such "trace" output is an essential diagnostic for programming, and would let you watch your program work....