Char arrays WITH spaces

Heya. I decided to make a simple CMD like program today, so I made a very simple String to Char array converter. However, whenever I use it, it returns a char array with the allocated length of the string (which is good), yet without spacing!

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
26
27
28
29
30
#include <stdlib.h>
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    while(true)
    {
        string* sInput = new string("");
        cin >> (*sInput);
        char * cInput;
        cInput = new char[sInput->length()];
        for(unsigned int i = 0; i < sInput->length(); i++)
            cInput[i] = (*sInput)[i];
        delete sInput;

        if (system(const_cast<char*> (cInput)) == -1)
        {
            cout << "Execution failed. (" << cInput << ")" << endl;
        }

        delete [] cInput;
    }
    return 0;
}


I'd like to know what I'm doing wrong and how I can make this work.

Thanks in advance,
Kyon
Why are you dynamically allocating sInput?
But anyway, there's c_str() and getline (which doesn't stop at a space unless you tell it to):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{
    while(true)
    {
        string input;
        getline(cin,input);
        if (system(input.c_str())!=0)
        {
            cout << "Execution failed. (" << input << ")" << endl;
        }
    }
}
Last edited on
Works a charm, thanks! Just one thing, why did my code not work? (Printing the string would still result in the spaces being shown)
You didn't put a zero terminator at the end of your cstring which is required to mark the end:

1
2
3
4
5

        cInput = new char[sInput->length() + 1]; // NOTE: + 1 to allow for the zero
        for(unsigned int i = 0; i < sInput->length(); i++)
            cInput[i] = (*sInput)[i];
        cInput[sInput->length()] = '\0'; // Add the terminating zero 
Topic archived. No new replies allowed.