Why my program won't loop?
Oct 21, 2012 at 8:55pm UTC
Below is my code, which works fine, with the exception of looping. I need to loop it so that the user will have option to enter the numbers again. Any help is appreciated.
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
#include<iostream>
#include<string>
using namespace std;
char Letter2Number(char );
int main ()
{
char ch='0' ;
char newLetters[11];
char letters[11];
while (ch !='#' )
{
cout<<"\nThis program converts letters to their corresponding telephone digits" <<endl;
cout<<"Enter a phone number: " ;
cin.get(letters, 11);
for (int j=0; j<11;j++)
{
if (letters[j]==' ' )
{
while (j<11)
{
letters[j]=letters[j+1];
j++;
}
}
}
cout<<"\nPhone Number before convert: " ;
cout << letters;
for (int i=0; i<11; i++)
{
if (i<3)
{
newLetters[i]=Letter2Number(letters[i]);
}
if (i==3)
{
newLetters[i]='-' ;
}
if (i>3)
{
newLetters[i]=Letter2Number(letters[i-1]);
}
}
cout<<"\nPhone Number after convert: " <<newLetters;
cout<<"\nTo stop the program enter #." ;
cin>>ch;
}
}
char Letter2Number(char letter)
{
switch (letter)
{
case 'A' :
case 'B' :
case 'C' :
case 'a' :
case 'b' :
case 'c' :
return '2' ;
break ;
case 'D' :
case 'E' :
case 'F' :
case 'd' :
case 'e' :
case 'f' :
return '3' ;
break ;
case 'G' :
case 'H' :
case 'I' :
case 'g' :
case 'h' :
case 'i' :
return '4' ;
break ;
case 'J' :
case 'K' :
case 'L' :
case 'j' :
case 'k' :
case 'l' :
return '5' ;
break ;
case 'M' :
case 'N' :
case 'O' :
case 'm' :
case 'n' :
case 'o' :
return '6' ;
break ;
case 'P' :
case 'Q' :
case 'R' :
case 'S' :
case 'p' :
case 'q' :
case 'r' :
case 's' :
return '7' ;
break ;
case 'T' :
case 'U' :
case 'V' :
case 't' :
case 'u' :
case 'v' :
return '8' ;
break ;
case 'W' :
case 'X' :
case 'Y' :
case 'Z' :
case 'w' :
case 'x' :
case 'y' :
case 'z' :
return '9' ;
break ;
/*case ' ':
return '\0';*/
default :
return letter; // in case it is not a letter or is already a number
break ;
}
}
Oct 21, 2012 at 9:07pm UTC
cin.getline leaves the new line character in the input buffer. So next time when the statements are executed
1 2
cout<<"\nTo stop the program enter #." ;
cin>>ch;
the new line character is read,
Also you program attempts to access memory outside the array.
Topic archived. No new replies allowed.