【发布时间】:2012-09-28 06:11:10
【问题描述】:
我在使用 atoi(s) 函数时遇到了一些问题。我正在尝试将命令行参数转换为整数,但是我从 atoi 函数接收到的整数表现得很奇怪。我检查了保存转换的变量,它们保存了正确的整数,但是当它们通过我的程序运行时,它们不能正常工作。该程序接受三个参数;程序本身、函数编号 (1-3) 和任意整数。例如,命令行指令看起来像 lab4p2 3 10。
功能:
#include <stdio.h>
#include <stdlib.h>
//---------------------------------------------------------------------------
// Functions
// Sumation function adds all integers from 1 to the value.
int sumation(int x)
{
int counter = 1;
int value;
while (counter < (x+1))
{
value += counter;
counter++;
}
return value;
}
// Negation function returns the negation of the given value.
int negation(int x)
{
int negator, value;
negator = (x*2);
value = (x - negator);
return value;
}
// Square function returns the square of the input value.
int square(int x)
{
int value;
value = (x*x);
return value;
}
//---------------------------------------------------------------------------
主要:
main(int argc, char *argv[])
{
int inputval, functionval, value;
double doubleval;
functionval = atoi(argv[1]);
inputval = atoi(argv[2]);
doubleval = atof(argv[2]);
printf("%i", functionval);
printf("%i", inputval);
if(argc != 3)
{
printf("%s", "Invalid amount of arguments! 3 expected. \n");
}
else if ((functionval < 1)||(functionval > 3))
{
printf("%s", "Invalid function value. Expected values: 1-3 \n");
}
else if (inputval != doubleval)
{
printf("%s", "Invalid value! Integer expected. \n");
}
else if (functionval = 1)
{
value = sumation(inputval);
printf("%s", "The sum from 1 to the input value = ");
printf("%d", value);
}
else if (functionval = 2)
{
value = negation(inputval);
printf("%s", "%d", "The negation of the input value = ", value);
}
else if (functionval = 3)
{
value = square(inputval);
printf("%s", "%d", "The square of the input value = ", value);
}
else
{
printf("%s", "Something is wrong!");
}
}
所有错误检查都正常工作,但从未访问过函数 2 和 3(尽管有输入),并且函数 1 显示的答案不正确。有谁知道问题可能是什么?
谢谢, 马特
【问题讨论】:
-
在你已经使用了
argv[1]和argv[2]之后,检查你是否拥有argc == 3;如果它们丢失,您的程序将会不愉快。您将同一参数转换两次,一次使用atoi(),一次使用atof()。通过赋值将inputval转换为double会更快。您的问题是else if (functionval = 1)将 1 分配给functionval然后检查它是否不为零(它不是!)。 -
谢谢,我调整了代码,以便在使用它们之前检查参数的数量。我同时使用 atoi 和 atof 的原因是我可以检查输入是否为整数,无论是:2 还是 2.0。 If doubleconversion != integer conversion then input is invalid.
-
您可以改用
strtol(),并检查是否在转换中使用了所有输入字符串。通常,当您不介意错误处理时使用atoi()和atof(),而当您介意错误处理时使用strtol()和strtod()。 -
编译时出现最大警告。例如,gcc -Wall 会发现这个错误。
标签: c command-line-arguments main atoi