c - Taking main argument
问题描述
I have a problem with my code. I would like to know what the "variation" value is. But it always gives me extremely high or negative values. So when I type in terminal for example ./NAME 3 I end up with another number. How can i fix it?
#include <stdio.h>
#include <cs50.h>
int main(int argc, string argv[])
{
int variation = (int)argv[1];
if (argc == 2)
{
printf("%i\n", variation);
return 0;
}
else
{
return 1;
}
}
解决方案
[注意:C
没有内置string
类型。有的是] C
_character array
这是一个非常容易解决的问题。这是给出的代码,它使用stdlib
's 内置atoi
函数转换string
为int
:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
char *var_str = argv[1];
int variation = atoi(var_str);
printf("variation: %d\n", variation);
}
else if (argc < 2) {
printf("no agrument provided.\n");
} else {
printf("only one argument was expected. %d provided.\n", argc);
}
return 0;
}
更新(使用更安全的版本strtol
):
asstrtol
是一个更好的转换string
为long int
,的函数atoi
,因为它是错误检测的utility
,所以最好strtol
在这方面使用。这种做法是由 user 严格执行的@klutt
。我要感谢她/他建议我也包含使用的代码strtol
。下面给出:
// a more secure version
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
char *var_str = argv[1];
char *text = NULL;
int base = 10; // default base
errno = 0; // intializing errno
long int variation = 0;
variation = strtol(var_str, &text, base);
// now on to error detection
// full error trace
if (var_str == text) {
printf ("error: no number found\n");
} else if (errno == ERANGE && variation == LONG_MIN) {
printf ("error: underflow\n");
} else if (errno == ERANGE && variation == LONG_MAX) {
printf ("error: overflow\n");
} else if (errno != 0 && variation == 0) {
printf ("error: unknown error\n");
} else if (errno == 0 && var_str && !*text) {
printf ("variation: %ld\n", variation);
} else if (errno == 0 && var_str && *text != 0) {
printf ("variation: %d, but some text included: %s\n", variation, text);
}
} else if (argc < 2) {
printf("no agrument provided.\n");
} else {
printf("only one argument was expected. %d provided.\n", argc);
}
return 0;
}
如果您有任何问题,请在评论中问我...
推荐阅读
- c++ - 在终端中正确输出 c++ windows wstring 日志
- javascript - 如果语句不适用于颜色代码
- awk - AwK 将较长的列与下一行对齐并保持相同的已处理行数/行数
- python - 条纹:遍历所有优惠券
- react-native - 反应图像内的本机文本
- c# - Unity Resolve 中的堆栈溢出异常
- angular - 本地化 i18n 字符串时如何排除其他元数据
- python - 切换路由器后,Pip 安装包不再适用于 RPi
- windows - 无法使用 v141_xp 工具集构建(无法安装 v7.1A SDK)
- arrays - 从文本文件中填充多维数组的最实用的方法是什么?