Reputation: 21
In C++ can I read from file which contains integers and store it in a char array[] ?
Upvotes: 0
Views: 379
Reputation: 58715
Yes, it is possible to store numbers from a file in a char
array:
#include <fstream>
#include <iterator>
#include <algorithm>
int main(int argc, char* argv[])
{
std::ifstream in("input.txt");
char arr[100];
char* end = std::copy(std::istream_iterator<int>(in),
std::istream_iterator<int>(),
arr);
return 0;
}
There are two issues here. One, you must know at compile time the size of your array. Two, each of the input numbers must fit into a char
. Note that this is formatted input, so the valid range is not 0-255 or even 0-127. It's a valid character, so '0', '2', 'a', 'C' and so on are valid inputs for each character.
Maybe what you want is to read your file into a std::vector<std::string>
?
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <string>
int main(int argc, char* argv[])
{
std::ifstream in("input.txt");
std::vector<std::string> vec;
std::copy(std::istream_iterator<int>(in),
std::istream_iterator<int>(),
std::back_inserter(vec));
std::transfrom(vec.begin(), vec.end(),
vec.begin(),
my_transform());
return 0;
}
Here we read the numbers into std::vector<std::string>
. Then, we manipulate each string representation of a number through the my_transform
functor. You define the functor as a simple struct that defines std::string operator()(const std::string&)
. The function-call operator takes a number and is expected to return the manipulation of the number, however you wish to change the number.
Upvotes: 3
Reputation: 8160
Yes. As long as your integers are small enough to be represented as a byte. If not, they higher order bytes will likely be lost.
Upvotes: 0