[英]Unexpected output in if & switch statements in C code
I cant figure out why either of the following code fails to operate as expected. 我无法弄清楚为什么以下代码中的任何一个无法按预期运行。 There both compiled into execution files.
两者都编译成执行文件。
Outputs: 输出:
a.out , prints 1, expected "no value"
a.out 1, prints 2, expected 1
a.out 2, prints 2, expected 2
Using a case: 使用案例:
void main(int in)
{
int a = in ;
printf("In function if\n");
if ( in == 1 )
printf("1\n");
else
if ( in == 2)
printf("2\n");
else
printf("wrong value\n");
}
Using a switch: 使用开关:
void main(int in)
{
switch( in )
{
case 1: printf("1\n"); break;
case 2: printf("2\n"); break;
default: printf("wrong value\n"); break;
}
};
I'm trying to get the following LISP functionality in C code: 我想在C代码中获得以下LISP功能:
(cond ((= in 1) 1)
((= in 2) 2)
(t nil))
Thank you for your assistance. 谢谢您的帮助。
main
doesn't accept the input from the command line as direct arguments, you are getting the argument count in there which is 1
if there are no arguments, and 2
if there is one argument, which causes the strange behavior. main
不接受来自命令行的输入作为直接参数,你在那里得到参数count,如果没有参数则为1
,如果有一个参数则为2
,这会导致奇怪的行为。
main
should be defined as int main( int argc, char *argv[] )
or something similar. main
应该定义为int main( int argc, char *argv[] )
或类似的东西。 To get the input, you need to first check if it exists by testing argc
(the argument count, plus one for the executable path), and then converting argv[1]
to an integer. 要获得输入,您需要首先通过测试
argc
(参数计数,加上可执行路径的一个)来检查它是否存在,然后将argv[1]
转换为整数。 atoi can be used to convert a string to an integer. atoi可用于将字符串转换为整数。
Note that the first parameter to main
is argc
, the total count of app name + parameters given on the command line. 请注意,所述第一参数
main
是argc
,应用名称+在命令行上给定参数的总数。 There is a second argument on main
, char *argv[]
for receiving the command line parameters. main
上有第二个参数, char *argv[]
用于接收命令行参数。
The reason you get the behaviour described is because your parameter in
replaces the purpose of argc
. 你描述的行为的原因是因为你的参数
in
取代的目的argc
。 ie when you execute the App with no command line params, the argc
count is 1, with one param, it will be 2, etc - this is the value passed to in
. 即当你使用任何命令行PARAMS执行应用程序时,
argc
数为1,一个PARAM,这将是2,等等-这是传递给该值in
。 Since you don't have a second main
parameter for the command line parameters ( argv
), you won't receive the actual parameters at all. 由于命令行参数(
argv
)没有第二个main
参数,因此根本不会收到实际参数。
To fix this, you'll need to parse the second args
array for your in
integer parameter: 为了解决这个问题,你需要解析第二
args
阵列为您in
整型参数:
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2)
return EXIT_FAILURE; // ... print out the correct command line usage to user
char *endPointer = NULL;
long in;
in = strtol(argv[1], &endPointer, 10);
if (endPointer != NULL) {
switch( in ) {
case 1:
// ... same code as above
}
return EXIT_SUCCESS;
}
return EXIT_FAILURE; // User hasn't provided a number for 1st param
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.