Use String in Switch
How does this work? I want to make a case in which the character A is given.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string code;
string number="";
int sz;
cin >> code;
sz = code.size();
for(int i=0;i>sz;i++)
{
switch(code[i])
case "A" : number=number+'10'; break; //Error here!
}
cout << number << endl;
return 0;
}
|
Did you mean to have i < sz here in the for loop?
for(int i=0;i>sz;i++)
If you're looking for a character, use single quotes in the case 'A'.
What are you meaning to do here? number=number+'10'
Did you mean to have i < sz here in the for loop?
for(int i=0;i>sz;i++) |
No. Why would i?
What are you meaning to do here? number=number+'10' |
To add the characters 1 and 0 to the number string.
Let's say I enter "Apple". sz would be 5. So for i starting at 0, i is not greater than sz or 5, so the code in the for loop will never execute.
To add the characters 1 and 0 to the number string. |
So make that a string "10" to append.
And you may need to put each case block in the switch within { } so the break statement doesn't break out of the for loop.
Let's say I enter "Apple". sz would be 5. So for i starting at 0, i is not greater than sz or 5, so the code in the for loop will never execute. |
Yes, sorry. Hard to focus right now.
And you may need to put each case block in the switch within { } so the break statement doesn't break out of the for loop. |
It gives me an error when i do it like this:
1 2 3 4 5 6 7
|
switch(code[i])
{
case 'A' : number=number+"10"; break;
case 'B' : number=number+"11"; break;
case 'C' : number=number+"12"; break;
}
|
Works fine like that. Thanks!
Last edited on
And you may need to put each case block in the switch within { } so the break statement doesn't break out of the for loop. |
No,
break
will break out of the nearest enclosing,
switch
,
for
,
while
, or
do
statement, regardless of whether it's inside
{}
.
Topic archived. No new replies allowed.