red
red

Reputation: 177

Formatted file reading with C++

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++.

Upvotes: 3

Views: 870

Answers (3)

Pulkit ShaRma
Pulkit ShaRma

Reputation: 67

// reading a text file the most simple and straight forward way
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;

int main () {
int a[100],i=0,x;
  ifstream myfile ("example.txt");
  if (myfile.is_open())  // if the file is found and can be opened
  {
    while ( !myfile.eof() ) //read if it is NOT the end of the file
    {

      myfile>>a[i++];// read the numbers from the text file...... it will automatically take care of the spaces :-)

    }
    myfile.close(); // close the stream
  }

  else cout << "Unable to open file";  // if the file can't be opened
  // display the contents
  int j=0;
  for(j=0;j<i;j++)
   {//enter code here
    cout<<a[j]<<" ";                 

 }
//getch();
  return 0;
}

Upvotes: 0

#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)
  );
}

Upvotes: 5

Pete Becker
Pete Becker

Reputation: 76245

int value;
while (std::cin >> value)
    std::cout << value << '\n';

In general, stream extractors skip whitespace and then translate the text that follows.

Upvotes: 1

Related Questions