Switch statement to convert number to word

Hello,
I have another program to write:
Write a program using a function and a switch statement. The user should be prompted to enter a number in main. The function is called and the number entered is passed to the function. This function parameter will then be used in a switch to discover and print out the number word within the function (for example, 1=one, 2=two, 3=three, etc.).
My code runs, but only shows "invalid number". Can you tell me what is my mistake?

Thank you for your help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

char number (int a) ;
 
int main ()
{
  
   int num ;
   char word ;
   cout << "Enter an integer number between 1 and 6.\n";
   cin >> num ;
   word = number (num);
   cout << "You entered " << word << endl;
 
   return 0;
}

char number (int a)
{
 switch(a)
   {
   case '1' :
      cout << "one" << endl; 
      break;
   case '2' :
      cout << "two" << endl;
   case '3' :
      cout << "three" << endl;
      break;
   case '4' :
      cout << "four" << endl;
      break;
   case '5' :
      cout << "five" << endl;
      break;
   case '6' :
      cout << "six" << endl;
      break;
   default :
      cout << "Invalid number." << endl;
   }
}
Well, there's a lot of things going on here that are wrong.

1) word should be a string, not a character; explained in the second point
2) the number function should return a string (characters are single-letter entities, and you want to deal with words here, not single letters)
3) each case should, instead of saying the number as a word, return the number as a word. So replace this:

1
2
cout << "one" << endl;
break;


with this:

return "one";

since your number function returns a string (or at least now does since you've followed point 2; previously, it returned a character) and if it doesn't return anything, that means that when you go in to display the contents of word on line 15, it will have gibberish inside.

4) The reason why your switch statement fails is because each of your cases is checking the integer input (say, 1) against a character ('1'). 1 is different from '1' is different from "1"; first is an integer, second is a character, third is a string. Get rid of the single quotes if you want the cases to be integers instead of characters.

5) Your default case should return "an invalid number" or something to deal with the newly-revised system of returning strings instead of displaying them in the function that should return strings.
Thank you Ispil.
It worked.
Topic archived. No new replies allowed.