Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How do I save argv to vector as strings

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;
}
like image 303
Bradley Petersen Avatar asked Jan 05 '23 22:01

Bradley Petersen


2 Answers

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.

like image 151
coyotte508 Avatar answered Jan 12 '23 22:01

coyotte508


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.

like image 38
Ajay Avatar answered Jan 12 '23 22:01

Ajay