我如何创建 const char* []
How I can create const char* []
我有代码:
int ParseCommandLine( int argc, const char* argv[])
{
string inFilePath = "";
string outFilePath = "";
for( int i = 1; i < argc; ++i )
{
if( string( argv[i] ) == "-i" || string( argv[i] ) == "--input")
{
// Check for "-i @args" form of reqest.
if( argc <= 2 )
{
ifstream newIn;
newIn.open(string(argv[++i]));
if(!newIn.is_open())
{
cerr << "Incorrect file path.";
return 1;
}
string buff;
vector<string> file;
while(newIn >> buff)
file.push_back(buff);
char** arr = new char* [file.size()];
for(int j = 0; j < file.size(); ++j)
arr[j] = file[j].c_str(); // Error: Assigning to 'char *' from incompatible type 'const std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::value_type *' (aka 'const char *')
ParseCommandLine(file.size(), arr); // Error No matching function for call to 'ParseCommandLine'
delete[] arr;
newIn.close();
return 0;
}
else
{
cerr << "Reqest with --input option can have only one argument." << endl;
return 1;
}
}
函数 ParseCommandLine 从主要参数中获取 argc&argv。这段程序需要将新文件转换为 const char* argv[] 然后调用 ParseComandLine.
有人可以帮忙解决这个问题吗?
只需将 char
更改为 const char
我有代码:
int ParseCommandLine( int argc, const char* argv[])
{
string inFilePath = "";
string outFilePath = "";
for( int i = 1; i < argc; ++i )
{
if( string( argv[i] ) == "-i" || string( argv[i] ) == "--input")
{
// Check for "-i @args" form of reqest.
if( argc <= 2 )
{
ifstream newIn;
newIn.open(string(argv[++i]));
if(!newIn.is_open())
{
cerr << "Incorrect file path.";
return 1;
}
string buff;
vector<string> file;
while(newIn >> buff)
file.push_back(buff);
char** arr = new char* [file.size()];
for(int j = 0; j < file.size(); ++j)
arr[j] = file[j].c_str(); // Error: Assigning to 'char *' from incompatible type 'const std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::value_type *' (aka 'const char *')
ParseCommandLine(file.size(), arr); // Error No matching function for call to 'ParseCommandLine'
delete[] arr;
newIn.close();
return 0;
}
else
{
cerr << "Reqest with --input option can have only one argument." << endl;
return 1;
}
}
函数 ParseCommandLine 从主要参数中获取 argc&argv。这段程序需要将新文件转换为 const char* argv[] 然后调用 ParseComandLine.
有人可以帮忙解决这个问题吗?
只需将 char
更改为 const char