3

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

William Pursell
  • 204,365
  • 48
  • 270
  • 300
red
  • 177
  • 1
  • 8

3 Answers3

5
#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)
  );
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1
int value;
while (std::cin >> value)
    std::cout << value << '\n';

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

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Would you mind explaining what this does? Sorry, I am new to C++ and the syntax is not too familiar – red Jun 21 '13 at 18:02
  • @red Useful search terms: stream extraction operators (or extractors), stream insertion operators (or inserters). – Angew is no longer proud of SO Jun 21 '13 at 18:05
  • @red - `std::cin` is the standard input stream; `std::cout` is the standard output stream. You read from an input stream with `>>`, and you write to an output stream with `<<`. Try it. And do the search that @Angnew suggested. – Pete Becker Jun 21 '13 at 18:48
0
// 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;
}