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?

Hi, Can you put an example of your .txt file?, in order to know the format.

:D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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

100000, numbers. it's called bsearch.txt.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.