Reputation: 1344
I have a txt file:
4286484840 4286419048 4286352998
(They are RGB values.)
I would like to store them in a vector.
void read_input(const char* file, std::vector<int>& input)
{
std::ifstream f(file);
if (!f)
{
std::cerr << file << "Read error" << std::endl;
exit(1);
}
int c;
while (f >> c)
{
std::cout << c << std::endl;
input.push_back(c);
}
std::cout << "Vector size is: " << input.size() << std::endl;
}
The result is:
Vector size is: 0
However with the following file:
1 2 3
The result is:
1
2
3
Vector size is: 3
What is wrong with the first file? Are the numbers too big?
Upvotes: 1
Views: 913
Reputation: 1
void read_input(const char* file, std::vector<unsigned long int>& input)
{
std::ifstream f(file);
if (!f)
{
std::cerr << file << "Read error" << std::endl;
exit(1);
}
int c;
while (f >> c)
{
std::cout << c << std::endl;
input.push_back(c);
}
std::cout << "Vector size is: " << input.size() << std::endl;
}
Upvotes: 0
Reputation: 103703
Yes, the numbers are likely too big. On the most common systems nowadays, int
is 32 bits, and its max value is 2^31-1
, although it's only guaranteed to be 2^15-1
(requiring 16 bits). You can check your limits with:
#include <limits>
#include <iostream>
int main()
{
std::cout << std::numeric_limits<int>::max();
}
In order to guarantee representation for values that large, you can use long long
. unsigned long
will do too, but barely. If you need integers of a specific size, I recommend you take a look at the <cstdint>
header.
Upvotes: 2