将字符串转换为 int (但前提是确实是 int)
在大学里,我被问到我们的程序是否检测到从命令行参数输入的字符串是否为整数,但它没有检测到(./Program 3.7
)。现在我想知道如何检测到这一点。因此,例如 a
的输入在 atoi 检测到时是无效的,但是像 3.6
这样的输入应该是无效的,但 atoi 会将其转换为整数。
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int number = atoi(argv[1]);
printf("okay\n");
}
}
但当然,只有当 argv[1] 确实是一个整数时才应该打印。希望我的问题很清楚。非常感谢。
In college I was asked if our program detects if the string enter from command line arguments is a integer which it did not(./Program 3.7
). Now I am wondering how I can detect this. So input as for example a
is invalid which atoi detects, but input like for example 3.6
should be invalid but atoi will convert this to an integer.
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int number = atoi(argv[1]);
printf("okay\n");
}
}
But offcourse okay should only be printed if argv[1] is really an integer. Hope my question is clear. Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看 strtol。
Have a look at strtol.
假设您想知道如何在代码中完成它(如果它确实是家庭作业,则可能),一种方法是考虑什么构成了字符串的整数。它很可能是:
根据该规范,您可以编写一个函数来为您完成这项工作。
像这样的伪代码将是一个好的开始:
Assuming you want to know how it could be done in code (possible if it is indeed homework), one way is to think about what constitutes an integer in terms of the string. It would most likely be:
From that specification, you can write a function that will do the work for you.
Something like this pseudo-code would be a good start:
所以你最好的选择是
strtof()
http:// publib.boulder.ibm.com/infocenter/zos/v1r10/topic/com.ibm.zos.r10.bpxbd00/strtof.htm
So your best choice is
strtof()
http://publib.boulder.ibm.com/infocenter/zos/v1r10/topic/com.ibm.zos.r10.bpxbd00/strtof.htm
编辑:允许 - 和 + 字符
您甚至可以将其压缩为密集的一行或两行。或者您可能会找到具有相同功能的库函数;)
编辑2:只是为了好玩 - 它现在应该解析数字
EDIT: allow - and + characters
You may even compress this into a dense one- or two-liner. Or you may find a library function with the same functionality ;)
EDIT2: just for fun - it should now parse the number