C ++使用命令行参数

时间:2012-01-27 01:04:05

标签: c++ command-line-arguments

我打算在命令行输入一个数字,例如说“./a.out 3”,其中3将是我正在尝试检索的数字。我想知道为什么在我的例子中,我试图输出的两个数字是不一样的,从命令行args中提取信息的最实用的方法是什么?感谢

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


    char* openSpace = argv[1];
    int temp = *openSpace;

    cout<<*openSpace<<" is the open spot!"<<endl;
    cout<<temp<<" is the open spot!"<<endl;

    return 0;
}

3 个答案:

答案 0 :(得分:8)

argv[1]char*,你需要一个int。不幸的是,您不能只改变变量的类型。相反,您必须将char*转换为int。使用atoi()功能。

int temp = atoi(argv[1]);

答案 1 :(得分:2)

你是什么意思,他们不一样?他们当然是!第一个将字符“3”打印为字符,第二个将其打印为整数。那就是你得到字符'3'的ASCII值。

如果您想获得整数值,可以使用atoi()strtol()boost::lexical_cast<int>()等内容。

答案 2 :(得分:1)

您无法使用int temp = *openSpace;之类的作业将字符串转换为整数。您需要为此调用一个函数,例如来自标准C库的atoi()