I am writing a C++ program to convert a number 1 - 9 to its word form. my piece of code is not working and i am getting the errors such as error:
case label ‘2’ not within a switch statement problem6.cpp:21: error: break statement not within loop or switch
How to fix this?
#include <iostream>
using namespace std;
int main()
{
char a = 0;
cout << "enter amount of money: ";
cin >> a;
switch (a)
case 1 :
cout << "one ";
break;
case 2 :
cout << "two ";
break;
case 3 :
cout << "three ";
break;
case 4 :
cout << "four ";
break;
case 5 :
cout << "five ";
break;
case 6 :
cout << "six ":
break;
case 7 :
cout << "seven ";
break;
case 8 :
cout开发者_StackOverflow中文版 << "eight ";
break;
case 9 :
cout << "nine ";
break;
return 0;
}
The reason for the error is that you didn't enclose the switch's cases within curly braces.
But I'm wondering why don't you define an array like this:
const char* numbers[] = {"zero", "one", "two", "three", .... etc};
And use it as:
//must check the validity of the range!
if ( a>=0 && a<=9 ) //or whatever the range you've defined.
cout << numbers[a];
Its also efficient, as Acme added in the comment.
You forgot the braces. Try
switch (a)
{
case 1 :
cout << "one ";
break;
case 2 :
cout << "two ";
break;
case 3 :
cout << "three ";
break;
}
Change your variable a
to an int
, or change all of your cases to their character equivalent (i.e., 1
to '1'
, 2
to '2'
etc).
Fixed Code:
int a = 0;
switch (a)
{ // Braces were missing
case 1 :
cout << "one ";
break;
case 2 :
cout << "two ";
break;
case 3 :
cout << "three ";
break;
case 4 :
cout << "four ";
break;
case 5 :
cout << "five ";
break;
case 6 :
cout << "six "; // You had a colon here instead of semi-colon
break;
case 7 :
cout << "seven ";
break;
case 8 :
cout << "eight ";
break;
case 9 :
cout << "nine ";
break;
} // end of switch
I agree with Nawaz. Use array its much more efficient.
You have to put all parts of the switch statement inside a pair of { }
switch(value)
{
case 1:
Something();
break;
case 2:
Etc.
}
This should work you had, amongst other things, missed a "}":
#include <iostream>
using namespace std;
int main()
{
char a = 0;
cout << "enter amount of money: ";
cin >> a;
int i = (int)a;
switch (i)
{
case 1 :
cout << "one ";
break;
case 2 :
cout << "two ";
break;
case 3 :
cout << "three ";
break;
case 4 :
cout << "four ";
break;
case 5 :
cout << "five ";
break;
case 6 :
cout << "six ":
break;
case 7 :
cout << "seven ";
break;
case 8 :
cout << "eight ";
break;
case 9 :
cout << "nine ";
break;
}
return 0;
}
精彩评论