Okay, so I'm supposed to write this program for school that takes a commercial number in letters, Like HOME CALL and convert it to its numerical form: 466-3255. But every time the program moves on to ask for the second number, the program crashes. I'm still very new to this so unable to decipher the errors. Any and all help will be greatly appreciated.
code:
#include <string>
#include <iostream>
#include <vector>
void convertnumber(std::string);
usingnamespace std;
int main()
{
char b;
do
{
cout << "Enter a telephone number expressed in letters to acquire the corresponding numeral number.\n";
string a;
a = "";
getline(cin, a);
convertnumber(a);
cout << "\nIf you want to process another number, enter \"Y\" or enter \"N\" to terminate program.\n";
cin >> b;
if (b == 'N')
cout << "Program Terminated.";
}
while (b != 'N');
}
void convertnumber(std::string a)
{
cout << "\n";
int i = 1;
char b;
for (i = 1; i <= 7; i++)
{
b = a[i];
if ((b == 'a') or (b == 'b') or (b == 'c') or (b == 'A') or (b == 'B') or (b == 'C'))
cout << "2";
if ((b == 'd') or (b == 'e') or (b == 'f') or (b == 'D') or (b == 'E') or (b == 'F'))
cout << "3";
if ((b == 'g') or (b == 'h') or (b == 'i') or (b == 'G') or (b == 'H') or (b == 'I'))
cout << "4";
if ((b == 'j') or (b == 'k') or (b == 'l') or (b == 'J') or (b == 'K') or (b == 'L'))
cout << "5";
if ((b == 'm') or (b == 'n') or (b == 'o') or (b == 'M') or (b == 'N') or (b == 'O'))
cout << "6";
if ((b == 'p') or (b == 'q') or (b == 'r') or (b == 's') or (b == 'P') or (b == 'Q') or (b == 'R') or (b == 'S'))
cout << "7";
if ((b == 't') or (b == 'u') or (b == 'v') or (b == 'T') or (b == 'U') or (b == 'V'))
cout << "8";
if ((b == 'w') or (b == 'x') or (b == 'y') or (b == 'z') or (b == 'W') or (b == 'X') or (b == 'Y') or (b == 'Z'))
cout << "9";
if (b == ' ')
cout << "0";
if (i == 3)
cout << "-";
}
i = 0;
}
errors:
Unhandled exception at 0x0FF3F2F6 (ucrtbased.dll) in task 1.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
string subscript out of range.
The program runs and converts the first input I give it, but the second I enter Y for it to ask for a second one, it shuts off.
It doesn’t like one of your function calls, but convertnumber(a) seems like a viable call, maybe check on getline(cin,a)? Also it seems like you are trying to access characters in your string (a) that don’t exist because you ran past the end of the array, try putting for(i = 0;i < a.length();i++){... instead of for(i = 0;i < 7;i++){...
Edit: also maybe getline is fucking with your cin?
Mixing cin>> and getline. The former leaves the newline character in the stream for the latter to pick up, erroneously.
Try either putting cin.ignore(1000,'\n');
immediately after your cin >> line
or change your getline call to getline( cin>>ws, a);
using std::ws to devour any whitespace, including a newline character.