Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatted file reading with C++

Tags:

c++

file-io

I am trying to read all integers from a file and put them into an array. I have an input file that contains integers in the following format:

3 74

74 1

1 74

8 76

Basically, each line contains a number, a space, then another number. I know in Java I can use the Scanner method nextInt() to ignore the spacing, but I have found no such function in C++.

like image 803
red Avatar asked May 03 '26 14:05

red


1 Answers

#include <fstream>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  int i;
  while (f >> i)
    arr.push_back(i);
}

Or, using standard algorithms:

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

int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  std::copy(
    std::istream_iterator<int>(f)
    , std::istream_iterator<int>()
    , std::back_inserter(arr)
  );
}
like image 176
Angew is no longer proud of SO Avatar answered May 06 '26 03:05

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!