I would like to write a C++ program to accept user input a sentence and remove all spaces. There are bugs.
input:ad jq jjwjfwwf
output:ad▀jq
input: dadad fff
output: dadad
#include<iostream>
using namespace std;
//using while loop to copy string
int main(){
int i=0;
int j=0;
char c[30];
char cc[30];
char ccc[30];
cin.getline(c,30);
while (c[i]!='\0')
{
cc[i]=c[i];
i++;
}
cc[i]='\0';
for (j=0;j<i;j++){
if (c[j]==' ')
{
continue;
}
if (c[j]=='\0')
{
break;
}
ccc[j]=c[j];
}
ccc[j]='\0';
cout<<cc<<'\n'<<ccc<<endl;
return 0;
}
You are trying far too hard. C++ has classes and library code that do this for you
As you can see, if you use the
std::stringtype then removing all the spaces is a single line of code.And even if you are trying to practise writing loops, you should still be using
std::stringinstead of achararray.