# File I/O question

## Recommended Posts

Hi. It's been a long time since I've delt with file io in c++. Can someone think of a good way to read in a file line that looks like: 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 into a 16 element int array? Thanks alot.

##### Share on other sites
If each number is only a 1 or a zero, just read in 31 bytes, and read every second byte.
Otherwise, just read chars into a buffer until you his a space, then use atoi() on the buffer to get the integer value.
I never do C++ I/O, I much prefer the C functions (fopen, fread, etc) so I can't help you with that aspect.

##### Share on other sites
I'm assuming you are trying to actually load in the binary data, not text :)

Well with the base file IO functionality the lowest you'll be able to load in are bytes (char, unsigned char) so load in the two of those and then you'll need to isolate each bit, something like.

for (i = 0; i < 8; i++)  // 8 bits per byte :){  if (byte & 0x80)       // read the highest bit (the 128 bit)  {     array[array_start + i] = 1;  }  else  {     array[array_start + i] = 0;  }  byte = byte << 1;      // next bit to higest}

for the first byte set array_start to 0, second one to 8.

you can also do this in reverse (load from lowest to highest) by simply checking if the byte is even or odd (byte % 2) then shift the other way.

Hope that helped

##### Share on other sites
Quote:
 Original post by dragonbideHi. It's been a long time since I've delt with file io in c++. Can someone think of a good way to read in a file line that looks like:0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0into a 16 element int array? Thanks alot.

if it's a text file and each of those values is sperated with whitespace then this will do it:

#include <algorithm>#include <iterator>#include <vector>#include <fstream>#include <iostream>int main() {   std::ifstream in("test.txt");   std::vector<int> vec_of_ints;   std::copy(std::istream_iterator<int>(in),             std::istream_iterator<int>(),             std::inserter(vec_of_ints, vec_of_ints.begin()));   std::copy(vec_of_ints.begin(),             vec_of_ints.end(),             std::ostream_iterator<int>(std::cout, ", "));   in.close();  return 0;}

##### Share on other sites
Sorry, it actually is a text input (doesn't have to be only 1's or 0's, could be any integer). what snk_kid was doing looks about right.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627698
• Total Posts
2978681

• 20
• 14
• 12
• 10
• 12