Reputation: 394
I have a file of very large numbers that will not fit into the int data type. My task is to take each individual digit of the large number and assign it to its own node in a linked list. I also need to read 2 large numbers at a time in the file, with each number in the file separated by a newline.
So far I have this for testing purposes:
inFile.open("file.txt");
inFile >> bigNumber;
for(const auto &c : bigNumber) {
cout << c << endl;
}
This prints the correct value, but the problem is it's a char and I cannot add or multiply this digit. How can I extract each individual digit from the string as an int?
I was also told that this is possible with a stringstream, though I don't know how these objects work at all? I'm very open to better/cleaner methods of doing the above task if possible.
Upvotes: 0
Views: 373
Reputation: 161
Depends on what you want to do:
To read the value as an ascii code, you can use
char c = 'a';
int i = (int) a;
/* note that the int cast is not necessary -- int i = a would suffice */
To convert the character '0' -> 0, '1' -> 1, etc, you can write
char c = '4';
int i = a - '0';
/* check here if i is bounded by 0 and 9 */
Upvotes: 2