我在我的一个函数中使用了 stoi,目的是将一串数字转换成一个整数。我的作业做了一半,但是我遇到了这个问题。奇怪的是,如果数字的字符数是偶数,那么 stoi 只转换前一半。如果有任何帮助,我将非常感激
代码。
#include <fstream>
#include <vector>
#include <string>
using namespace std;
string start;
string endD;
int sDigit;
int eDigit;
int i;
vector<int> palindromes;
void construct(int layer, int digits, string prev)
{
string temp = prev;
if(layer > (digits % 2) + digits/2)
{
short a = (short) digits/2;
for(int i = a; i >= 0; i--)
{
if(i == a && digits % 2 == 1)
{
continue;
}
else
{
temp.push_back(temp[i]);
}
}
cout << temp << " " << stoi(temp) << endl; // Output is here
palindromes.push_back(stoi(temp));
}
else if(layer == 1 && digits == sDigit)
{
for(int i = start[0] - '0'; i < 10; i++)
{
temp[0] = i + '0';
construct(layer + 1, digits, temp);
}
}
else if(layer == 1 && digits == eDigit)
{
for(int i = '1'; i <= endD[0]; i++)
{
temp[0] = i;
construct(layer + 1, digits, temp);
temp = prev;
}
}
else if(layer == 1)
{
for(int i = 1; i < 10; i++)
{
temp[0] = '0' + i;
construct(layer + 1, digits, temp);
temp = prev;
}
}
else
{
for(int i = 0; i < 10; i++)
{
temp.push_back(i + '0');
construct(layer + 1, digits, temp);
temp = prev;
}
}
}
int main()
{
int startD, endDD;
cin >> startD >> endDD;
start = to_string(startD);
endD = to_string(endDD);
int tempS = startD;
int tempE = endDD;
while(tempS != 0)
{
tempS /= 10;
sDigit++;
}
while(tempE != 0)
{
tempE /= 10;
eDigit++;
}
for(int i = sDigit; i <= eDigit; i++)
{
construct(1, i, "x");
}
for(int i = 0; i < palindromes.size(); i++)
{
//cout << palindromes[i] << endl;
}
}```
Input: 1 1000
Output:
你的代码有未定义的行为,因为在这一行中
temp.push_back(temp[i]);
您正在访问 temp
出界。你可以通过添加一行
std::cout << "check " << i << " " << temp.size() << "\n";
在该行之前。
输出将是(见 此处):
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
check 1 1
check 0 2
1
...
当尺寸为 1
最后的有效指数是 0
. 问题不在于 stoi
但以你的算法逻辑。