Read in numbers and calculate

Hello guys, beginner here and i was wondering if i could get your guys' help on something im working on. Ive been trying to read in a number(and eventually a bunch of numbers) from a text file and calculate certain digits from that number, like the number will be 16 digits long and i want to multiply the 15 digit by 2. It reads in the number just fine but whenever i multiply it by 2 it won't work right. Help please.
Also i am using devc++.


Last edited on
You read in the entire number as a string. That's ok.
Then select a specific digit and assign it to a char variable. That's ok too.

But multiplying a character by 2 doesn't make sense. The number is stored probably in ASCII code, so that character '0' = 48 decimal, '1' = 49 and so on.

Thus, if you want to do any calculation, you first need to convert the character to an integer. A simple way is to do this:
int number = character - '0'; as long as you are sure that the character variable definitely contains a digit 0 to 9.
Last edited on
ahh that would explain the weird answers i have been getting.

Also I am assuming the splitting the int into two separate digits if it is greater than 9 no longer applies to that correct?

Here is what i am doing:


it seems to be working pretty well
Last edited on
I'm not quite sure what you mean about the int greater than 9.

If the source of the value was a single character in the file, it should result in an integer 0 to 9. The only case where it might be bigger than 9 is where the character was non-numeric (e.g. a letter of the alphabet, or punctuation etc).

Of course, if you multiply by 2, or do other calculations, you may end up with more than a single digit.
Last edited on
Also one last question i promise!

Why does it cout the numbers twice? I'm guessing it is because of the while loop. I have everything working correctly except for that. There is only one set of 16 digit numbers in there and when i run it, it computes those same numbers twice.
I would like to add a bunch more in there which seems to work fine when i do.
there were some calculations in between where i would multiply every other number by 2 and check if it was greater than 9 or not. But i got it to work fine thank you!

But it keeps running the last set of numbers twice before the program ends.
How are you determining when you're done with your loop? That might help locate the problem.
I am using

while(!inputFromFile.eof())
Never mind guys i got it.
I used while(inputFromFile << num)

instead and so that worked thanks for the help guys!
Topic archived. No new replies allowed.