Karnivaurus
Karnivaurus

Reputation: 24121

Reading an ASCII file with fstream

Have an ASCII text file with some integer numbers in it, each separated by a space, and sometimes the numbers go on to a new line. For example:

// my_file.txt
23 45 973 49
44 1032 33 99
43 8 4 90824

I want to read 100 of these numbers into an array of "ints". Thus far, I have the following code:

int x[100];
fstream file_in("my_file.txt", ios::in);
for (int i = 0; i < 100; i++)
{
    file_in >> x[i];
}

However, I now want to do a couple of other things that I am not sure about.

  1. What if I want to just read the entire file in, without having to go through the loop? If this was binary data, I know that I can just write file_in.read((char*)&x[0], 100 * sizeof(int)). But how can I do this with an ASCII file?

  2. What if I want to skip the first 3 numbers in the file, and start reading from the fourth? Again, if this was binary data, I could just use file_in.seekg(3 * sizeof(char)). But I don't know how to skip in an ASCII file.

Upvotes: 1

Views: 1974

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477110

No raw loops!

Reading the entire file:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream f("data.txt");
    std::vector<int> v(std::istream_iterator<int>(f), {});

Skipping over the first three:

   v.erase(v.begin(), v.begin() + 3);

Upvotes: 3

Related Questions