I seem to be having a problem with a for loop, in creating a linear search of a .txt file.
What I am aiming to do is to have the output "Found @ literal position(s):" to be displayed twice if the same element is found at different positions in the .txt file.
Instead of outputting the former, the code seems to only output the statments:
"Enter a number to find in the array: Entered Number "
"To quit enter 1000"
And after it is outputted the code loops.
I believe the source of the problem is the if statement I created.
1 2 3 4 5 6
for (int i = 0; i<SIZE; i++)
{
if (myArray[i] == arryNum)
cout<<"Found @ literal position(s):" <<results<<endl;
}
#include<iostream>
#include<string>
#include<fstream>
usingnamespace std;
int linearSearch(constint [], int, int);
int main()
{
constint SIZE = 99;
int myArray[SIZE], i[SIZE];
ifstream file("Linear Numbers.txt");
if (!file)
{
cout << "The Text File Will Not Open!" << endl;
return 1;
}
int results;
int arryNum;
do
{
cout<<"Enter a number to find in the array: ";
cin>>arryNum;
results = linearSearch(myArray, SIZE, arryNum);
for (int i = 0; i<SIZE; i++)
{
if (myArray[i] == arryNum)
cout<<"Found @ literal position(s):" <<results<<endl;
}
cout<<"To quit enter 1000"<<endl;
}while(arryNum != 1000);
return 0;
}
int linearSearch(constint array[], int size, int value)
{
int index = 0;
int position = -1;
bool found = false;
while (index < size && !found)
{
if(array[index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
void SeeBytesTXT()
{
cout << "####### SEE BYTES #######\n";
streampos Begin, End;
ifstream myfile("example.txt");
Begin = myfile.tellg();
myfile.seekg(0, ios::end);
End = myfile.tellg();
cout << (End - Begin) << " bytes.\n";
myfile.seekg(0, ios::beg); // Return to beginning
while (myfile.tellg() < End && myfile.tellg() >= 0)
{
unsignedchar Read; // Read[size] if you want to get more than one byte
myfile.read((char*)&Read, sizeof(Read)); // Read "size" byte stream of a file
/*
add your arguments here!
*/
}
myfile.close();
}
void SeeBytesTXT()
{
cout << "####### SEE BYTES #######\n";
streampos Begin, End;
ifstream myfile("example.txt");
Begin = myfile.tellg();
myfile.seekg(0, ios::end);
End = myfile.tellg();
cout << (End - Begin) << " bytes.\n";
myfile.seekg(0, ios::beg); // Return to beginning
while (myfile.tellg() < End && myfile.tellg() >= 0)
{
int Read;
myfile.read((char*)&Read, sizeof(Read)); // Read "size" byte stream of a file
if (Read == arryNum)
{
found = true;
position = myfile.tellg();
}
}
myfile.close();
}
In an example, I'll copy paste my code to find a string in a binary file (note that i already have a header position defined and some functions and classes are defined but not visible, but ignore it):