C++ Convert VERY long number in string to int

lets say

string z = "6544654165456434685413546545312144165464561246546545241231654564654231324165451201654654351111111111111111555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666677777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777779999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999";

int convert(string &z , int &sum){

for (int i = 0; i<z.length(); i++){
sum+=stoi(z[i]);
}

return sum;
}



why this doesnot work ? it throws stupid errors and freezers VS , so ? i would like to do sum of the numbers its exactly written , sum += value of current element converted to string , please help me
So, you want to get sum of all digits in number?

Note that stoi() converts string to integer. And string's operator[] returns char.
i wrote a program that write in text file value of number for example 5^1500

and now im gonna count the element for example lets say

5^1500 = 12345

and what im looking for is 1 + 2 + 3 + 4 + 5

i have already converted this huge number to string , now i would like to do that if the number is in char array i would like to do sum+=char[i]- '0';

but how to do the same with string ?
Err, same way?
sum+=z[i] - '0';
exactly thats what i did but , unfortunately the number wrote to my text file is

10715086071862676000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000








but in real the number of 2 on 1000 is different ......


and also where might be the problem ????,









ofstream myfile;

myfile.open("xyz.txt");

myfile<<fixed<<pow (x,y);;
myfile<<fixed<<pow (x,y); This is not going to work for large values. Floating point numbers are imprecise by their design. They have precision: maximum amount of significant digits. For double it is around 16 decimal digits. So only around 16 first digits are correct.
If you want to operate on large numbers, you will need bigint library, or write one yourself.
Topic archived. No new replies allowed.