Home > Enterprise >  How to search a file using an array as search term
How to search a file using an array as search term

Time:04-15

I'm trying to parse a csv file and search it to find values that match my randomly generated array.

I've tried a few methods but im getting lost, I need to access the entire file, search for these values and output the index column that it belongs to.

my code for my random array generator as well as my search csv function:

EDIT:

edited code to make reproducible, with added comments, hopefully this matches criteria (besides given csv file obviously).

reproducible example:

#include <fstream>
#include <iostream>
#include <string>
#include <random>

using namespace std;


//fills array of size 6 with random numbers between 1-50
void random_array(int arr[]){
 
    for(int i=0;i<6;i  )
    {
        int num = rand()Q;
        arr[i]=num;
    }

}

int main(){
    string line;
    fstream file;
    
    int size = 6;
    int numbers[size];
    int found;

    //gets random array from random_array func
    srand(time(NULL));
    random_array(numbers);

    //opens file to search
    file.open("CSV directory here");
    if(file.is_open())
    {
        //print random array values
        for(int i = 0; i < size; i  ){
            cout << numbers[i]<< " ";}
            cout << endl;
        
        //get file contents and search if contents of array exist in file
        while(getline(file, line)){
            
           for(int i = 0; i < size; i  ){
            found = line.find(std::to_string(numbers[i]));

           if(found != string::npos) {
               //print found numbers
               cout << found << " ";
           }
        }
      }
            
    }

    return 0;
} 

CSV format:

,Date,1,2,3,4,5,6,7
0,Wed 03 January 2001,5,6,16,17,19,22,40
1,Sat 06 January 2001,6,16,23,34,35,40,37

my output:

array generated:

35 35 38 37 16 31

numbers found:

26 33 33 39 24 31 34 33 24 6 28 31 33 33 30 0 32 34 33 30 27 38 26 29 29 33 7 24 29 26 26 26 24 24 0 30 30 36 0 0 23 27 0 0 7 36 36 27 30 30 27 27 26 26 32 29 23 38 32 32 28 28 7 25 29 37 25 29 29 26 23 34 31 28 25 31 28 28 34 32 32 35 38 40 25 37 37 35 40 40 30 30 42 42 42 36 35 28 31 25 37 7 27 36 33 36 33 29 39 29 35 34 34 40 40 43 31

CodePudding user response:

I'd recommend looking at the find function in more detail. None of its overloads take in an integer, the nearest match (and one that would be used) takes in a char ... So it would not be looking for strings like "12" it would be looking for the character which has a value of 12.

You need to first convert the number(s) to a string. A simple modification would be:

for ( int i = 0; i < 6; i   ) {
   if( (offset = line.find( std::to_string( numbers[i] ) ) ) != string::npos ) {
       //do something
   }
}
  • Related