【发布时间】:2015-05-20 11:39:44
【问题描述】:
我正在尝试在 C++ 中创建一个命令行应用程序,并且我想确保输入是某个命令参数之后的整数。
对于这个例子,我想检查“-p”命令参数之后的下一个参数是否是一个整数。这是我现在的代码的 sn-p。
while (count < argc){
if (strcmp("-p", argv[count]) == 0){
has_p = true; //Boolean
pid = atoi(argv[count + 1]);
if (pid == 0 && argv[count + 1] != "0" ){
err = 1;
cout << "pid argument is not a valid input" << endl;
pid = -1;
}
count++;
}
...
}
现在这段代码正确地捕捉到了这个输入中的错误:
- -p 1777
- -p sss
- -p sss17
- -p [空格] -U
但在这种输入格式下失败
- -p 17sss
我试图通过使用 sprintf 进行比较来解决这个问题。不幸的是,为 sprintf 提供 char 数组指针仅在 buffer2 中输出 1 个字符。
while (count < argc){
if (strcmp("-p", argv[count]) == 0){
has_p = true; //Boolean
pid = atoi(argv[count + 1]);
sprintf(buffer, "%d", pid);
sprintf(buffer2, "%d", *argv[count + 1]);
if (pid == 0 && argv[count + 1] != "0" || (buffer != buffer2) ){
err = 1;
cout << "pid argument is not a valid input" << endl;
pid = -1;
}
count++;
}
...
}
有没有办法让 sprintf 读取整个 char 数组?如果没有,除了循环指针直到我点击“\0”
之外,还有更好的解决方案吗?【问题讨论】:
-
选择一种语言。你说的是 C++,但你使用的是 C 习语,问题是用两者来标记的。
-
使用
strcmp比较两个字符串,而不是!=。您可以使用if( isdigit(argv[count]) )来检查参数是否为数字。 -
哦,我的错。我在 Visual Studio 2013 中编程,所以我将它标记为 c++。但我也希望它在 c 中编译。
-
更新“我也希望它在 c 中编译” - 然后删除 C++ 标签。 // 对于 C++,boost 的
lexical_cast<int>(argv[count + 1])是一个不错的选择 - 如果无法从文本中解析出int,或者之后有垃圾文本,它会抛出异常......