You can avoid nested if statements with the else if clause:
if ( sentence[i] == '0' )
cout<<"zero";
else if ( sentence[i] == '1' )
cout<<"one";
else if ( sentence[i] == '2' )
cout<<"two";
else if ( sentence[i] == '3' )
cout<<"three";
else if ( sentence[i] == '4' )
cout<<"four";
else if ( sentence[i] == '5' )
cout<<"five";
else if ( sentence[i] == '6' )
cout<<"six";
else if ( sentence[i] == '7' )
cout<<"seven";
else if ( sentence[i] == '8' )
cout<<"eight";
else if ( sentence[i] == '9' )
cout<<"nine";
Or with a switch statement:
switch ( sentence[i] ) {
case '0': cout<<"zero"; break;
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;
}
Alternatively, a table based approach is generally easier to get right:
string number[] = {
"zero","one","two","three","four","five","six","seven","eight","nine"
};
cout<< number[sentence[i] - '0'];
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
In the OP sentence was declared thus:
string sentence[size];
Therefore, in the syntax used by the OP sentence is an array of string of size size. Therefore to refer to a given char of a given string you would need to use multidimensional []s. However, why use that syntax? It's much easier to just use:
string sentence;
and then use the routine single dimension [] to refer to a given char within sentence. This is what Narue apperas to have to used in her demonstrations.
The point of the post/original question was how to convert the value of a given char or a given int into a word of English. The techniques presented can be modified to whatever syntax you need/wish.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
Also note, in the OP, that
int size = 6;
string sentence[size];
is illegal as the size of a static array needs to be specified using a constant value, not a variable. To use a variable to declare memory for an array you must use dynamic memory, not static. This is just another reason to use a single string, not an array of strings. And again, since it wasn't the meat of the question, it is more for your education, than to answer the original question.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
>I can't believe Narue hasn't commented on this...
Narue has a day job that saps a lot of her time. :rolleyes: Anyway, any similarity between my examples and a complete solution is purely coincidence. If any code that I post doesn't compile, then chances are good that the intention was to convey an idea, and it's your job to integrate the idea into your code. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401