Val G.
Val G.

Reputation: 141

command prompt in c++

Guys what am I doing wrong here?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    while (true){
        std::string cmd;
        cin >> cmd;

        const char* com = cmd.c_str();

        cout << com << endl;
       // cout << sizeof(com) << endl;

        system(com);
    }
    return 0;
}

Everytime I run this it works fine but when you type something like cd ../ it separates the words and runs them as two different commands so first cd, then ../ and it gives me a error. Any idea on what I'm doing wrong? I'm new to C++ anyway also this is supposed to bypass "command prompt has been disabled by your admin on windows"

Upvotes: 0

Views: 721

Answers (1)

Raindrop7
Raindrop7

Reputation: 3911

the extraction operator (>>) stops reading when reaching the first white-space if your command consists of spaces then use std::getline:

std::string sCommand;
std::cout << "Enter eommand: ";
std::getline(std::cin, sCommand); // eg enter: color 1f
system(sCommand.c_str()); // c_str(): converts from class string to const char*.

there's no way to pass two arguments one after the other to system when the first arguments invokes a program and the second is passed to it but you can make on big command then pass it.

system("diskpart"); // invoking diskpart
system("list vol"); // here list vol is not passed to diskpart but only to cmd  

system("notepad.exe C:/desktop/mylog.txt"); // ok

Upvotes: 1

Related Questions