Function/For loop help
Mar 19, 2018 at 9:15pm UTC
I am trying to write a program that will translate phone numbers with letters in them into only numbers (ex. 1-800-flowers --> 1-800-3569377), but i am only getting blank lines or random numbers in return
1 2 3 4 5 6 7 8 9 10
5 #include <iostream>
6 #include <string>
7
8 char letter(char ch)
9 {
10 switch (ch)
11 {
12 case 'A' :
13 case 'a' :
14 case 'B' :
---------- every case and number is then listed ----
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
93 return 9;
94 break ;
95
96 case '1' :
97 return 1;
98 break ;
99
100 case '0' :
101 return 0;
102 break ;
103
104 }
105 }
106
107 #include <iostream>
108 #include <string>
109 using namespace std;
110
111 int main()
112 {
113 int length, i;
114 char ch;
115 string phone, result;
116
117 length = phone.length();
118
119 cout << "Enter the phone number" << endl;
120 cin >> phone;
121
122 for (i = 0; i < length; i++)
123 {
124 ch = phone.at(i);
125 letter(ch);
126 cout << ch;
127 }
128
129
130 return 0;
131 }
ive tried switching around variables but i'm really trying to get this function to work and its pissin me off
Mar 19, 2018 at 10:06pm UTC
1 2 3 4 5 6
for (i = 0; i < length; i++)
{
ch = phone.at(i);
letter(ch);
cout << ch;
}
You pass “ch” by copy and than you don’t save letter() return value.
You'd better not to declare any variable until you need it: you could easily get rid of many of yours.
Compare:
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
// Provided:
// 2abc 3def
// 4ghi 5jkl 6mno
// 7pqrs 8tuv 9wxyz
#include <iostream>
#include <string>
char letter(char ch);
int main()
{
std::cout << "Enter the phone number: " ;
std::string phone;
std::cin >> phone;
for (size_t i = 0; i < phone.length(); ++i) { std::cout << letter(phone.at(i)); }
std::cout << '\n' ;
return 0;
}
char letter(char ch)
{
switch (ch)
{
case 'A' : case 'a' : case 'B' : case 'b' : case 'C' : case 'c' :
return '2' ;
case 'D' : case 'd' : case 'E' : case 'e' : case 'F' : case 'f' :
return '3' ;
case 'G' : case 'g' : case 'H' : case 'h' : case 'I' : case 'i' :
return '4' ;
case 'J' : case 'j' : case 'K' : case 'k' : case 'L' : case 'l' :
return '5' ;
case 'M' : case 'm' : case 'N' : case 'n' : case 'O' : case 'o' :
return '6' ;
case 'P' : case 'p' : case 'Q' : case 'q' : case 'R' : case 'r' : case 'S' : case 's' :
return '7' ;
case 'T' : case 't' : case 'U' : case 'u' : case 'V' : case 'v' :
return '8' ;
case 'W' : case 'w' : case 'X' : case 'x' : case 'Y' : case 'y' : case 'Z' : case 'z' :
return '9' ;
default : return ch;
}
}
Topic archived. No new replies allowed.