字符串中相同数字的单独序列

Edg*_*r.A 6 c++ string

我正在尝试做一个小任务,要求将数字转换为电话键盘的字母,例如,如果输入为222则表示电话按钮"2"(http://upload.wikimedia.org/wikipedia/commons/7/ 7d/Telephone-keypad.png)被推3次,输出应该是"C"等等.首先,我应该做的是将所有序列分开,例如22255-444分为222,55, - ,444和然后我认为把一切都搞清楚,但现在问题是我的功能无法读取最后的序列

#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;
}
Run Code Online (Sandbox Code Playgroud)

作为测试我现在使用这个输入:5552-22-27777,输出应该是555 2 - 22 - 2 7777,但对我来说它是555 2 - 22 - 2 2 2 2 2.

int*_*jay 2

在这份if声明中:

if(text[i] != text[j] || j == text.size())
Run Code Online (Sandbox Code Playgroud)

第二个条件 ( j == text.size()) 永远不会为真,因为循环将在此之前终止。因此,当到达字符串末尾时,result和的值i将不会正确更新。

您可以做的就是从循环中删除终止条件(没有必要有终止条件,因为无论如何您都会跳出循环)。并且您需要颠倒中条件的顺序,if以便您不会读取超过字符串末尾的内容:

for(j = i; ;j++)
{
    if (j == text.size() || text[i] != text[j])
    ...
Run Code Online (Sandbox Code Playgroud)