C++ reading in integers, delimited by commas problem

I have a file that has data like:

1,0,3,5,7,4,2,7,8,1,5,2,1,4,7,8,

These are just arbitrary numbers for the sake of example, but the values will never be more than 2 digit integers.

I've run into several problems with this. It only accepts characters, so I'm not sure how to read in a two digit integer. Even worse, is my code to read in single digit integers is still not working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	string filename = "test.txt";

	file.open(filename, ifstream::in);

	int i = 0;
	char buffer[16];

	if(file.is_open())
	{
		while(file.good())
		{
			file.getline(&buffer[i],  3, ',');
			file.ignore(1);
			i++;
		}
		file.close();
	}


Last edited on
You don't need to do anything complicated, you can just use the formatted extraction operator because of the way it reads numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
std::vector<int> numbers;
if(std::ifstream in {"test.tct"})
{
    int x;
    while((in >> x) && in.ignore()) //read number, ignore comma, repeat
    {
        numbers.push_back(x);
    }
}
else
{
    //failed to open file
}
Note that this assumes that the last character in the file is a comma as per your example. If the last character is not a comma, the last number will not be read with this code.
Last edited on
I will also add that for the limitation of the digit value you can use bit field . That is nice because you can specify how many bits you want to use and the number of bits will decide of the available value range 8 bits ( an unsigned byte/char) has a maximum value of 255.
@Ericool: I actually recommend not doing what you suggested because from the point of view of the user, powers of two are arbitrary numbers.
yes you are right. :)
Topic archived. No new replies allowed.