[英]C++ std::logic_error within for loop using argv
I am new to C++ and I am trying to write a program to take in command line arguments and produce a .desktop file. 我是C ++的新手,我正在尝试编写一个程序以接受命令行参数并生成一个.desktop文件。 I am trying to implement identification of the argv values but I keep getting a std::logic_error 我正在尝试实现argv值的标识,但我不断收到std :: logic_error
My code is: 我的代码是:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
string name;
string comment;
for(int i = 1; i <= argc; i++) {
char* tmp[] = {argv[i]};
string param = *tmp;
string paramVal = argv[i+1];
if(param == "-h") {
cout << "-h Display this help dialogue" << endl;
cout << "-n Set entry name" << endl;
cout << "-c Set entry comment" << endl;
cout << "-e Set entry executable path" << endl;
cout << "-i Set entry icon" << endl;
break;
}
else if(param == "-n") {
name = paramVal;
i++;
continue;
}
else if(param == "-c") {
comment = paramVal;
i++;
continue;
}
else if(param == "-e") {
}
else if(param == "-i") {
}
else {
cout << "ERROR >>> Unrecognised parameter %s" << param << endl;
}
}
cout << "Name: %s\nComment: %s" << name << comment << endl;
return(0);
}
The program compiles fine (using g++) but when I try to run ./createDesktopIcon -na -cb
I get the following error 该程序可以正常编译(使用g ++),但是当我尝试运行./createDesktopIcon -na -cb
,出现以下错误
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted
Please help as it is very frustrating 请帮助,因为它非常令人沮丧
Here are the problems I see: 这是我看到的问题:
i <= argc
You want to compare i < argc
because the argv[argc]
element in the array is actually one past the last element in the argv
array. 要比较i < argc
因为argv[argc]
数组中的元素实际上是一个过去的最后一个元素argv
阵列。
Also, here: 也在这里:
string paramVal = argv[i+1];
This will access the array out of bounds as well. 这也将超出范围访问数组。
You might want to look at getopt to do all of this for you. 您可能想看看getopt为您完成所有这些工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.