4

I am trying to save argv into a vector as strings but I keep getting the error: see reference to function template instantiation 'std::vector<_Ty>::vector<_TCHAR*[]>(_Iter,_Iter)' being compiled

I have tried Save argv to vector or string and it does not work

I am using Microsoft Visual Studio 2010.

Here is my code:

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<std::string> allArgs(argv + 1, argv + argc);
    return 0;
}
Community
  • 1
  • 1
  • 1
    Most likely you need to use the non MSVS version of `main` like `int main(int argc, char* argv[])` – NathanOliver Jun 08 '16 at 18:54
  • 6
    If you're compiling with unicode, _TCHAR is a wide character which requires a std::wstring instead of a std::string. – kfsone Jun 08 '16 at 18:56
  • Since you are using Visual Studio, you may not need to store those values at all. They are available throughout your applications using the [__argc, __argv, __wargv](https://msdn.microsoft.com/en-us/library/dn727674.aspx) symbols. – IInspectable Jun 08 '16 at 20:02

2 Answers2

5

The problem is that std::string doesn't have a constructor for the _TCHAR* type, so you can't generate a vector of strings from an array of _TCHAR*.

Try using as said by @NathanOliver the "normal" version of the main: int main(int argc, char *argv[]).

Or switch to std::wstring.

Note: If not compiling with unicode enabled, _TCHAR* may then be equivalent to char * and the code would not provoke any compiler errors.

coyotte508
  • 9,175
  • 6
  • 44
  • 63
4

Use this:

typedef std::basic_string<TCHAR> tstring;
// Or: 
   // using tstring = std::basic_string<TCHAR>;
// If you have latest compiler

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<tstring> allArgs(argv + 1, argv + argc);
    return 0;
}

And if you would always want to use wide-strings, use this

  int wmain(int argc, whar_t* argv[])
  {
        std::vector<std::wstring> allArgs(argv + 1, argv + argc);
        return 0;
  }

Or, if you want to have ANSI only (I'd not recommend), just use old style char and main.

Ajay
  • 18,086
  • 12
  • 59
  • 105