I made a program which converts n decimal numbers sk into other numerical system p but sometimes it crashes and the error code I get is 0xC0000005 (program still converts and outputs all the numbers) . One thing I just noticed that it happens then converted number is longer than 6 symbols (or it's just a coincidence).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
long n,sk,p,j;
string liekanos;
ifstream f("u1.txt");
f >> n;
for (int i=0;i<n;i++)
{
f >> sk >> p;
j=0;
while (sk>0)
{
liekanos[j]=sk % p;
sk/=p;
j++;
}
for (j>=0;j--;)
{
if (liekanos[j]<10)
cout<<int(liekanos[j]);
else cout<<char(liekanos[j]+55);
}
cout<<endl;
}
return 0;
}
Example input:
3
976421618 7
15835 24
2147483647 2
With liekanos[j]
you access element at index j
but since you haven't specify size of this string, you are most likely trying to access non-existing element. You could call liekanos.resize(sk)
before you enter your while
loop to make sure it never happens.
Or if you know the maximum possible size of liekanos
, you could declare it as string liekanos(N, c);
where N
is its size and c
is the default value of each character in it.
您正在得到未定义的行为,因为liekanos
字符串永远不会有任何大小或容量。
string liekanos;
By default string has zero size. But you try to
liekanos[j]=sk % p;
Better use std::vector<char> liekanos;
instead of string liekanos;
. You'll need to do some modifications in your code:
for (int i=0; i<n; i++)
{
std::vector<char> liekanos;
f >> sk >> p;
while (sk>0)
{
liekanos.push_back(sk % p);
sk/=p;
}
for (long j = liekanos.size(); j>=0; --j)
{
if (liekanos[j]<10)
cout<<int(liekanos[j]);
else cout<<char(liekanos[j]+'a');
}
cout<<endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.