system commands with char's

Okay so i'm trying to get this c++ program to run commands on cmd.
Anyway I have got it working though I can't seem to figure out how to use char's in printing to the system. I.e

#include <iostream>
using namespace std;
#define NL '\n'
int main()
{
char lol[50];
cout << "Please enter what you want to enter into cmd";
cout << NL;
cin >> lol;
system("net send" lol)
}

I seem to get an error with adding a second part to the system part.
I can have it by itself I.e
system(lol);
That would work fine but I can't have two for some reason...
Please help!
Thanks
Kingpulse
In C++, you cannot concatenate (i.e. join together) two char arrays by simply putting them next to each other.

You have chosen to use C style arrays of char instead of proper C++ strings, which is making things difficult for yourself, but not too difficult.

You can concatenate C strings (char arrays) with the strcat function. I recommend you switch to C++ strings, which are far easier to work with.
You need a single string. So use strcat() to join them. http://www.cplusplus.com/reference/cstring/strcat/

Alternatively use C++ strings, such as
system(text.c_str()); where text is a c++ string.
Okay thanks :D , but do you think you could give me an example as to how its used? I'm new to c++ and it would be really helpful.
Thanks
Kingpulse
note that system is evil and should not be used but since ur new...

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

using namespace std;

#define NL \n

int main()
{
    string inputString, command;
    unsigned long length;
    
    command = "net send";
    length = strlen(command.c_str());
    
    getline(cin, inputString);
    
    strncat(command.c_str(), inputString.c_str(), length)
    
    system(command.c_str());
}
Example using c-strings:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
    char prefix[] = "net send ";
    char line[80];
    char buf[100];
    cout << "Please enter cmd" << endl;
    cin.getline(line, 80);

    strcpy(buf, prefix);
    strcat(buf, line);

    system(buf);
    
    return 0;
}


Now the same thing using C++ strings. Notice you don't need to specify the length of the string. The calls to strcpy and strcat are much simpler - see line 12 below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string prefix = "net send ";
    string line;
    cout << "Please enter cmd" << endl;
    getline(cin,line);

    string buf = prefix + line;

    system(buf.c_str());

    return 0;
}
Last edited on
@ Aramil of Elixia
this line isn't correct. The destination cannot be written to:
strncat(command.c_str(), inputString.c_str(), length);
(it looks like a mutant hybrid of C and C++ code).
Last edited on
mhhhhm i wasn't thinking yeah so just turn command into a null ptr
Topic archived. No new replies allowed.