Parsing a large number into individual ints

I have a text file with a large number and I want to store each individual digit in a vector.

for example, with file "file.txt"
 
123456789

I tried to use a simple code that works when there is whitespace between each digit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <fstream>
#include "test.h"

using namespace std;

int main()
{
	ifstream text;
	int hold;
	vector<int> vec;
	text.open("file.txt");
	while(text>>hold)
	{
		vec.push_back(hold);
		cout<<hold;
	}
        text.close();
        cout<<vec.size();
	return 0;
}


however the only output is zero, the size of vector "vec". I am trying to have vec[0]=1, vec[1]=2, vec[2]=3, vec[3]=4, vec[4]=5 etc.

Any help is appreciated
I tried to use a simple code that works when there is whitespace between each digit.
however the only output is zero
Did you tried it on file when there is whitespace between digits? If so, you have problems opening file. Check if file opened correctly.

To get your file read to work correctly without whitespaces, read each digit in char and convert it to number:
1
2
3
4
5
char temp;
while(text >> temp && isdigit(temp)) {
    vec.push_back(temp - '0');
    std::cout << temp;
}
Is the part
temp-'0'

what converts char to int?
Thanks a lot, appreciate it
I would tackle this program by simply reading the input in as a string. Then individual elements in the string can be parsed by referencing the element location...

1
2
3
4
5
6
7
8
9
10

string input;

fin >> input;

for (int i = 0; input[i]; i++)
{
    cout << input[i] << endl;
}


And then if you want to be able to use these individual numbers, convert it to an int as such:

1
2
//n represent any possible element in the string
int number = input[n]
Last edited on
Topic archived. No new replies allowed.