2012-01-27 138 views
1

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

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; 
} 

回答

8

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

int temp = atoi(argv[1]); 
+1

看看boost的lexical_cast也。 – 2012-01-27 01:09:14

2

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

如果你想要得到它不能转换字符串的整数值,你可以使用类似atoi()strtol()boost::lexical_cast<int>()

+0

不要忘记'std :: stoi' – 2012-01-27 01:09:26

1

使用像int temp = *openSpace;赋值为整数。您需要为此调用一个函数,如标准C库中的atoi()