CoderDake
CoderDake

Reputation: 1547

Character by Character Input from a file, in C++

Is there any way to get input from a file one number at a time? For example I want to store the following integer in an vector of integers since it is so long and can't be held by even a long long int.

12345678901234567900

So how can I read this number from a file so that I can:

vector<int> numbers;
number.push_back(/*>>number goes here<<*/)

I know that the above code isn't really complete but I hope that it explains what I am trying to do. Also I've tried google and so far it has proved innefective because only tutorials for C are coming up which aren't really helping me all too much.

Thank is advance, Dan Chevalier

Upvotes: 1

Views: 221

Answers (3)

Matt K
Matt K

Reputation: 13872

You can read a char at a time with char c; cin.get(c); and convert it to the numeral with c -= '0'. But perhaps you can just read it as a string or use something like BigNum.

Upvotes: 0

user461697
user461697

Reputation:

Off the top of my head this should fill up a character array which you can then iterate through. I realize it's not exactly what you were after but it's my preferred method.

void readfile(char *string)
{
    ifstream NumberFile; 
    NumberFile.open("./Number"); //For a unix file-system
    NumberFile >> string;
    NumberFile.close();
}

Also, to perform operations on the actual numbers you can use:

CharacterArray[ElementNumber] - '0'

and to get the number when it is small enough to fit in a datatype you add each element of the array multiplied by 10 to the power of its index.

Upvotes: 0

Cubbi
Cubbi

Reputation: 47478

This could be done in a variety of ways, all of them boiling down to converting each char '0'..'9' to the corresponding integer 0..9. Here's how it can be done with a single function call:

#include <string>
#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
#include <algorithm>
int main()
{
        std::string s = "12345678901234567900"; 
        std::vector<int> numbers;
        transform(s.begin(), s.end(), back_inserter(numbers),
                  std::bind2nd(std::minus<char>(), '0'));
        // output
        copy(numbers.begin(), numbers.end(),
             std::ostream_iterator<int>(std::cout, " "));
        std::cout << '\n';
}

When reading from a file, you could read the string and transform(), or even transform() directly from istream iterators, if there is nothing else in that file besides your number:

    std::ifstream f("test.txt");
    std::vector<int> numbers;
    transform(std::istream_iterator<char>(f),
              std::istream_iterator<char>(),
              back_inserter(numbers),
              std::bind2nd(std::minus<char>(), '0'));

Upvotes: 1

Related Questions