How to make this work
#include <stdio.h>
#include <conio.h>
main()
{
char C;
printf("R=This Program gives you some of the information of the country you entered.");
printf("Enter a Country:");
scanf("%c", &C);
switch(C)
{
case 'Algeria':
printf("Capital: Algiers");
printf("Currency and Country Code: Algerian Dinar (DZD)");
break;
}
getch ();
return 0;
}
The Error is
11 8 C:\\Users\\Edrian\\Desktop\\C++ Codes\\World Information.cpp [Warning] character constant too long for its type
C:\\Users\\Edrian\\Desktop\\C++ Codes\\World Information.cpp In function 'int main()':
11 8 C:\\Users\\Edrian\\Desktop\\C++ Codes\\World Information.cpp [Warning] case label value exceeds maximum value for
type
Know the difference :
'Algeria' this is a string literal so it should be "Algeria" and your C should be a string
'A' is a character
Char 只包含一个字符,如果您想使用多个字符,则必须使用字符串数据类型。在您的情况下,您应该使用字符串
11 8 C:\\Users\\Edrian\\Desktop\\C++ Codes\\World Information.cpp [Warning] character constant too long for its type
This says that 'Algeria'
is too long for the type char
, which should be a single letter, eg 'A'
(as suggested here ).
char string[256];
scanf("%255s", string);
switch (s[0]) {
case 'A':
if (0 == strcmp(string, "Algeria")) {
This should work. You may need to #include <string.h>
for strcmp
.
Notice how "Algeria"
is now double-quoted, while 'A'
is single-quoted.
I elided out lines that would be the same in both, mostly printf
statements. Make sure that you get the curly braces right. I added a {
for the if
. You'll need to add a }
to match (before the break;
).
You could also say
if (!strcmp(string, "Algeria")) {
But I thought that it might be easier for you to read the other way. Functionally the two statements are the same, as C considers zero to be falsey.
See also:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.