2

I have a string array of 3 different command line commands. Instead of writing out 3 system functions I am trying to learn how to pass a string array that holds these commands to the system function (or a similar function i.e. exec()) in a for loop. I am having trouble trying to figure out how to pass this string array into the system function one at a time. The goal is to get to exit status of each one and to break the for loop if returning an error.

            std::string arrString[3] = {"something","another thing","a final thing"}
            int i;
            for(i=0; i<3; i++)
            {
                if (system(/*Something*/))
                ;//Do something...
            }     

EDIT: This outputs that an error happened, but it shouldn't.

                std::string arrString[4] = {"cmd","cmd","cmd"};
            int i;
            for(i=0; i<3; i++)
            {
                if (system(arrString[i].c_str())==0) {
                    OutputDebugStringW(L"It works!");
                }
                else
                {
                    OutputDebugStringW(L"It doesnt work :(");
                }
            }   

3 Answers 3

3

system takes char*, so you need to call c_str on each element of your array:

std::string arrString[3] = {"something","another thing","a final thing"}
int i;
for(i=0; i<3; i++) {
    if (system(arrString[i].c_str())) {
        //Do something...
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Worked how I needed. Thank you. On a side note, what would be the best way to check if exit status was successful? See my edit above*
system(...) returns whatever the command has returned. Usually commands return zero on success, but the exact value is system-dependent. You can assign the return code to an int variable, and check that value to decide if the run has been successful or not.
So using something like if (system(arrString[i].c_str())==0) would not be the best option? I have heard that system()'s return is not always reliable. I am just trying to find the best possible solution.
system()'s return value is not quite that simple. The return value is in the same format as the wait or waitpid system calls. You may only care whether it's zero, though.
@mkb: So do you suggest I look into the documentation for wait and waitpid?
|
0
system(arrString[i])

Then check exit code and break the loop if appropriate.

Comments

0

You have to convert std:string to a char* first by using the c_str() function:

system(arrString[i].c_str())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.