[英]A simple C switch statement program error. I cant build and run it. I don't know why
I'm new to C an programming and I'm trying a piece of code from a book. 我是C语言编程的新手,我正在尝试一本书中的一段代码。 When I try to build and run it, I get errors and warnings that unable me to run the program.
当我尝试构建和运行它时,出现错误和警告,提示我无法运行该程序。 Not sure why.
不知道为什么。 My code is written verbatim.
我的代码是逐字编写的。 I'm also using codeBlocks for PC.
我也在PC上使用codeBlocks。
#include <stdio.h>
int main()
{
char choice;
printf("Are you filing a single, joint or ");
printf("Married return (s, j, m)? ");
do
{
scanf(" %c ", &choice);
switch (choice)
{
case ('s') : printf("You get a $1,000 deduction.\n");
break;
case ('j') : printf("You geta 1 $3,000 deduction.\n");
break;
case ('m') : printf("You geta $5,000 deduction.\n");
break;
default : printf("I don't know the ");
printf("option %c.\n, choice");
printf("Try again.\n");
break;
}
}while ((choice != 's') && (choice != 'j') && (choice != 'm');
return 0;
}
The error is because of the missing )
in While
statement. 该错误是由于
While
语句中缺少)
。
Currently it is: while ((choice != 's') && (choice != 'j') && (choice != 'm');
当前是:
while ((choice != 's') && (choice != 'j') && (choice != 'm');
it should be 它应该是
while ((choice != 's') && (choice != 'j') && (choice != 'm'));
Apart from that you have issues with your scanf
and printf
statements. 除此之外,您的
scanf
和printf
语句还有问题。
Currently they are: scanf(" %c, &choice");
当前它们是:
scanf(" %c, &choice");
and 和
printf("option %c.\\n, choice");
These should be changed to : scanf(" %c", &choice);
这些应更改为:
scanf(" %c", &choice);
and 和
printf("option %c.\\n", choice);
These type of issues can be easily avoided if taken care while writing the code. 如果在编写代码时格外小心,可以轻松避免此类问题。
You have several syntactical problems. 您有几个语法问题。
In your scanf
line, the closing double quote is in the wrong place, it should be after %c
. 在
scanf
行中, scanf
双引号放在错误的位置,应该在%c
。
scanf(" %c", &choice);
In you while
line, you are missing a closing parenthesis at the end of the line. 在
while
行中,您在行末缺少左括号。
} while ((choice != 's') && (choice != 'j') && (choice != 'm'));
Fixing both of these errors causes the program to compile and run fine for me. 修复这两个错误会导致程序编译并可以正常运行。
In function 'main':
Line 25: error: expected ')' before ';' token
Line 27: error: expected ';' before '}' token
Line 27: error: expected declaration or statement at end of input
http://codepad.org/tXK1DlsJ http://codepad.org/tXK1DlsJ
First of all, you don't close the braces of your do-while loop. 首先,您不必关闭do-while循环的花括号。 You need to add the braces at the end.
您需要在末尾添加大括号。
while ((choice != 's') && (choice != 'j') && (choice != 'm'));
Additionally, as other people have mentioned you need to change your scanf statement to 此外,正如其他人提到的那样,您需要将scanf语句更改为
scanf(" %c", &choice);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.