raja raja - 1 month ago 5
C++ Question

Not able to convert string into an char array

I am new to c++
So, i am trying to convert string with spaces in to an array of char with out spaces

here is what i tried

string str;
cout << "Enter a string: ";
getline(cin, str);
int TempNumOne=str.size();
char Filename[100];
for (int a=0;a<=TempNumOne;a++)
{
cout<<str[a]<<endl;
if(str[a]!=' ')
Filename[a]=str[a];
}

cout<<Filename;


the out put in console looks like this

Enter a string: hello world
h
e
l
l
o

w
o
r
l
d

hello


only hello is getting stored
why is this happening and how to solve this
please someone help me in this...

Answer

This is because:

  if(str[a]!=' ')
          Filename[a]=str[a];

In "hello world", str[4] is o, and str[6] is w. The above code will: store the o into Filename[4] and the w into Filename[6], instead of Filename[5]. A computer only does what you tell it to do, and now what you want it to do. Your logic did skip over the space, but all it did is that it didn't copy it into the corresponding position into the Filename buffer. This is not enough to accomplish the given task.

To do this correctly you need to maintain a separate index variable, call it b, for example, initialize it to 0, then:

 if(str[a]!=' ')
      Filename[b++]=str[a];

and don't forget to null-terminate the Filename, at the end.

Comments