I'm trying to do a little task which asks to convert numbers to letters of phone keypad, for example if input is 222 it means phone button "2" ( http://upload.wikimedia.org/wikipedia/commons/7/7d/Telephone-keypad.png ) is pushed 3 times and output should be "C" and etc. So first thing what i should do is to separate all the sequences, for example 22255-444 into 222 , 55 , - , 444 and then i think figure everything out, but now problem is that my function can't read last sequence
#include <iostream>
#include <fstream>
using namespace std;
//-------------------------------------------------------------------------
void encode(string text, string &result, int &i)
{
char keyboard[10][4] = {
{' ',' ',' ',' '},
{'.','?','!','.'},
{'a','b','c','a'},
{'d','e','f','d'},
{'g','h','i','g'},
{'j','k','l','j'},
{'m','n','o','m'},
{'p','r','q','s'},
{'t','u','v','t'},
{'w','x','y','z'}
};
int j;
for(j = i; j<text.size();j++)
{
if(text[i] != text[j] || j == text.size())
{
result = text.substr(i, j-i);
i = j-1;
break;
}
}
cout << result << endl;
}
int main()
{
ifstream fd("sms.in");
string text;
string result;
getline(fd, text);
for(int i = 0; i<text.size();i++)
{
encode(text, result, i);
}
return 0;
}
as a test now im using this input : 5552-22-27777 , output should be 555 2 - 22 - 2 7777, but for me its 555 2 - 22 - 2 2 2 2 2.
In this if
statement:
if(text[i] != text[j] || j == text.size())
The second condition (j == text.size()
) will never be true because the loop will terminate before that. So when you reach the end of the string, the values of result
and i
will not be updated correctly.
What you can do is remove the termination condition from the loop (it's not necessary to have one because you will break out of the loop anyway). And you will need to reverse the order of the conditions in the if
so that you don't read past the end of the string:
for(j = i; ;j++)
{
if (j == text.size() || text[i] != text[j])
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With