How to remove multiple spaces from a C++ program and put one space instead it
c++
Solution
`cin` truncates the string whenever it encounters a space. To read the entire line use `getline()`. Also I recommend using `std::string`.
std::string str;
std::getline(std::cin,str);
for(i=str.size()-1; i >= 0; i-- )
{
if(str[i]==' '&&str[i]==str[i-1]) //added equal sign
{
str.erase( str.begin() + i );
}
}
Loop iterates from the end so that 1. The `str.size()` complication is removed. 2. A bit of efficiency is introduced in the erase operation (if there are a lot of spaces).
Problem
How to remove multiple spaces from a C++ program and put one space instead it? What I tried was:- ``` #include<iostream> using namespace std; int main() { char str[80],i, j; cin>>str; for(i=0; i!='\0'; i++) { if(str[i]=' '&&str[i]==str[i+1]) { for(j=i+1; str[j]!='\0'; j++) str[j-1]=str[j]; } } cout<<str; } ```