copy a string (with spaces) to char array

I'm having trouble copying a string with spaces to a char array.

If the string does not contain spaces everything works fine (see below):

My input was: "hello"

Enter a string: hello
hello
Press any key to continue . . .


However if my input is: "h e l l o"
this is what I get:

Enter a string: h e l l o
h
Press any key to continue . . .


What's going on here?

This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string exp;
    char * array;
    
    cout<<"Enter a string: ";
    cin>>exp;
    array = new char[ exp.length() ];
    
    for( int i = 0; i < exp.length(); i++)
    {
         array[i] = exp[i];
         cout<<array[i];
    }
    cout<<endl;

system("pause");
return 0;

}


Can you guys help me, please?
The problem is not with copying the array (although I am not sure why you are doing that in the first place) but with the way that you are extracting from the stream. You want to use getline so that it extracts the entire line up to the carriage return. Use the debugger and look at the value returned by exp.length(). Moreover the for loop is not necessary. The stream operator<< can handle the entire array in one line of code whether you send it the whole string object or the c-array. One more thing. When copying strings the length does not include the null. You need to manually add a null at the end so technically the copy operation is not correct either. You need length() + 1 and to insert the null at the end.

getline(cin, exp); // this will do the trick for you.

for instance

1
2
3
4
5
std::cout << exp << std::endl;  // works

char* array = new char[exp.length() + 1];
strcpy(array, exp.c_str());
std::cout << array << std::endl;
Last edited on
Try getline: http://www.cplusplus.com/reference/string/getline/
operator >> stops at the first whitespace

Too slow...
Last edited on
Thank you.

I need this because I'm trying to make a program that evaluates postfix expressions and I feel that this is the easiest approach.
Topic archived. No new replies allowed.