这道题,我也一直在报错runtime error,这种问题主要是因为数组越界,溢出
注意,电话号码可能是0000033这种0开头的转化成数字时,前面的0会消失变为33,这样在给数字最后加‘-’时就会越界报runtime error
下面是我的代码
#include<iostream>
#include<map>
#include<string>
#include<fstream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<cstring>
using namespace std;
int main()
{
//ifstream fin("C:\\Users\\ZSM\\Desktop\\now\\test\\input1002.txt");
int n;
cin >> n;
string s;
vector<long> list;
if (n == 0)
{
cout << "No duplicates.";
return 0;
}
while (n--)
{
cin >> s;
string str="";
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '-')
continue;
else if (s[i] == 'A' || s[i] == 'B' || s[i] == 'C')
str.push_back('2');
else if (s[i] == 'D' || s[i] == 'E' || s[i] == 'F')
str.push_back('3');
else if (s[i] == 'G' || s[i] == 'H' || s[i] == 'I')
str.push_back('4');
else if (s[i] == 'J' || s[i] == 'K' || s[i] == 'L')
str.push_back('5');
else if (s[i] == 'M' || s[i] == 'N' || s[i] == 'O')
str.push_back('6');
else if (s[i] == 'P' || s[i] == 'R' || s[i] == 'S')
str.push_back('7');
else if (s[i] == 'T' || s[i] == 'U' || s[i] == 'V')
str.push_back('8');
else if (s[i] == 'W' || s[i] == 'X' || s[i] == 'Y')
str.push_back('9');
else if (s[i] >= '0'&&s[i] <= '9')
str.push_back(s[i]);
}
long num = atoi(str.c_str());
list.push_back(num);
}
sort(list.begin(),list.end());
map<long, long>num;
map<long, long>::iterator it;
int i = 0;
vector<long>temp;
while (i < list.size())
{
while (i + 1<list.size()&&list[i] == list[i + 1])
{
it = num.find(list[i]);
if (it == num.end())//没找到
{
num[list[i]] = 2;
temp.push_back(list[i]);
}
else
num[list[i]]++;
i++;
}
i++;
}
if (temp.size() == 0)
{
cout << "No duplicates.";
}
else
{
for (int i = 0; i < temp.size(); i++)
{
ostringstream oss;
string str;
oss << temp[i];
str = oss.str();
if (str.size() != 7)
{
int m=7 - str.size();
while (m--)
{
str.insert(str.begin(), '0');
}
}
str.insert(str.begin() + 3, '-');
cout << str << ' ' << num[temp[i]] << endl;
}
}
system("pause");
return 0;
}