raja raja - 1 month ago 6
C++ Question

Not able to convert string into a char array

I am trying to convert a string with spaces into an array of char without 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 output 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 do I solve 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