6

So now I have a

int main (int argc, char *argv[]){}

how to make it string based? will int main (int argc, std::string *argv[]) be enough?

6 Answers 6

27

You can't change main's signature, so this is your best bet:

#include <string>
#include <vector>

int main(int argc, char* argv[])
{
    std::vector<std::string> params(argv, argv+argc);
    // ...
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, +1 from me, although usually you want argv+1, argv+argc (because argv+0 is the application name).
@sbi, yeah- that's important to keep in mind, but I was trying to keep it simple :)
4

If you want to create a string out of the input parameters passed, you can also add character pointers to create a string yourself

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{

string passedValue;
for(int i = 1; i < argc; i++)
 passedValue += argv[i];
    // ...
    return 0;
}

1 Comment

The "+=" would mash them all together. passedValue.append(argv[i]).append(" ") would look nicer.
3

You can't do it that way, as the main function is declared explicitly as it is as an entry point. Note that the CRT knows nothing about STL so would barf anyway. Try:

#include <string>
#include <vector>

int main(int argc, char* argv[])
{
    std::vector<std::string> args;
    for(int i(0); i < argc; ++i)
        args.push_back(argv[i]);

    // ...

    return(0);
}; // eo main

3 Comments

vow. like that i(0) syntax +1
Since you know the size of the resulting vector, you could use vector's size constructor to preallocate, avoiding possible multiple reallocations with .push_back(). You could also use vector's iterator constructor to avoid having to write the loop yourself.
@luke, yup I saw your response and +1'd it as it is far cleaner than mine.
3

That would be non-standard because the Standard in 3.6.1 says

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { /* ... */ }

and

int main(int argc, char* argv[]) { /* ... */ }

1 Comment

@Chubsdad : I use Foxit ;-)
2

No. That is not allowed. If present, it is mandated to be char *argv[].

BTW, in C++ main should always be declared to return 'int'

Comments

2

main receives char*. you will have to put the argv array into std::strings yourself.

1 Comment

main does not pass anything. instead, main is passed char* by the CRT

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.