0

Hey Guys,
I have a text file that has numbers in it. And I need the program I am working on to search it as an array. How do I do that?

2
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by fjrivash
0

Excuse me but do you know the amount of numbers that you have to read from the file?.. let me know.

0

Hi again,

I think this is what you need, may be it needs some tweaks but this works, at least as I tested :P

test.cpp

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string>
#include <iostream>
#include <istream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <iomanip>

using namespace std;

int main()
{

  int t;
  int* a = NULL;
  int size = 100000;
  int i = 0;
  string nameFile;
  a = new int[size];

  cout << "Insert File name" << endl;
  cin >> nameFile;

  ifstream file(nameFile.c_str()); // reading the file

  if (file.is_open()) // Open file operation succees
  {
    while (file >> t)
    {
      a[i] = t;
      i++;
    } 

    for (int i = 0; i<size;i++)
    {
      cout << a[i] << endl;
    }
    delete[] a;
    a = NULL;
    file.close();
  }
  else cout << "File" << nameFile << "can not be opened" << endl;

  return 0;
}

and

Makefile
test : test.cpp
  g++ test.cpp -o test

and then $make and run ./test

Note : May be you do not need some of those libraries

I hope this can help you.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.