0

This is my requirement -

I have to get the inputs from Command line in the form

-des <destIP> -prot <tcp/udp> -min <minutes>

There are several programs that suggest how to parse these values through the argc and argv parameters of main() function. But I want a function which gets the iput line and then parse it.

The function would be -

void GetArguments()
{
    cout << "Enter arguments ..." << endl;
    cin >> inputStr;//eg: inputStr = "-des 127.0.0.1 -prot tcp -min 60"

    //code to parse the input arguments and get values of dest IP, protocol and time
}

How do I get the values I need?

1
  • You'll need to pass the arguments of the main() function to this function (GetArguments()). There's no other way to get the input line. Commented Aug 19, 2014 at 6:49

1 Answer 1

2

Use CommandLineToArgvW() to parse a wchar_t*, such as from a std::wstring, into a wchar_t*[] array that you can loop through, just like with argv/argc. For example:

void GetArguments()
{
    std::wstring inputStr;
    std::wcout << L"Enter arguments ..." << std::endl;
    std::wcin >> inputStr;

    int numArgs;
    LPWSTR *args = CommandLineToArgvW(inputStr.c_str(), &numArgs);
    if (args)
    {
        for (int i = 0; i < numArgs; ++i)
        {
            // use args[i] as needed...
        }
        LocalFree(args);
    }
}

This is a Windows-specific solution, since your question is tagged for Visual Studio. If you are looking for a pure C++ solution, you will have to tokenize inputStr manually, splitting it on whitespace and quotations as needed. There are tons of examples of that floating around.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the header that I need to include for LPWSTR and CommandLineToArgvW()?
If you read the documentation I linked you to, it tells you that CommandLineToArgvW() is declared in Shellapi.h. As for LPWSTR, it is declared in WinNT.h, which is included by Windows.h.

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.