Reputation: 1290
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
Upvotes: 2
Views: 4465
Reputation: 469
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;
}
Upvotes: -1
Reputation: 42083
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.
Upvotes: 3
Reputation: 495
string liekanos;
By default string has zero size. But you try to
liekanos[j]=sk % p;
Upvotes: 1
Reputation: 62063
You are getting undefined behavior because your liekanos
string never has any size or capacity.
Upvotes: 1