[英]Convert char to bool (passing bool to main)
Is there a recommended/correct/safer way to pass a bool argument to your main function? 有没有推荐/正确/安全的方法来将bool参数传递给您的main函数?
Are this 是这个吗
$ ./my_software true
with this as my_software
: 以此为
my_software
:
int main(argc, argv* []){
bool my_bool = argv[1];
return 0;
}
and this 和这个
$ ./my_software 1
with this as my_software
: 以此为
my_software
:
int main(argc, argv* []){
bool my_bool = atoi(argv[1]);
return 0;
}
equivalent? 当量? Am I missing a conversion in the first one?
我是否在第一个错过转换?
C++ streams can handle this. C ++流可以处理此问题。 Don't forget to check that
argv[1]
actually exists ! 不要忘记检查
argv[1]
确实存在!
#include <sstream>
//...
std::stringstream ss(argv[1]);
bool b;
if(!(ss >> std::boolalpha >> b)) {
// Parsing error.
}
// b has the correct value.
Putting in the std::boolalpha
stream manipulator enables parsing "true" and "false", leaving it out will let it parse "0" and "1". 放入
std::boolalpha
流操纵器将启用对“ true”和“ false”的解析,将其保留将使其解析“ 0”和“ 1”。
As for correct ways to do it, there's a lot. 至于正确的方法,有很多。 But there are unsafe/incorrect ways that you propose.
但是,您提出了一些不安全/不正确的方法。 First you are not guaranteed that
argv
is of length 2 or higher, you have to check argc
before even looking at argv[1]
(or anything in argv
. 首先,不能保证
argv
的长度为2或argc
,甚至在查看argv[1]
(或argv
任何内容)之前,都必须检查argc
。
Second you're not guaranteed to get particular content in argv[1]
even if it does exist. 其次,即使确实存在
argv[1]
也不能保证会得到它。 It could be any string, not only the expected "0"
or "1"
(it could even be the empty string) so just running it through atoi
is probably not a wise choice. 它可以是任何字符串,不仅是预期的
"0"
或"1"
(甚至可以是空字符串),因此仅通过atoi
运行它可能不是明智的选择。
Yes, you're missing a conversion on the first example, and most compilers should issue a diagnostic. 是的,您在第一个示例中缺少转换,并且大多数编译器应发出诊断信息。 The code won't work anyway, even if it compiles, because it tries to convert a raw character pointer to a bool value, and won't even look at the contents of the string.
该代码即使编译也无法正常工作,因为它试图将原始字符指针转换为bool值,甚至不查看字符串的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.