mimiholli mimiholli - 2 months ago 9
C++ Question

how to count a specific number from a file in c++

Yes, this is a question for a class, but I don't want my homework done for me. I just need to figure out where I'm going wrong. The question that I have to figure out states this:

Write a program which uses the file produced in Lab 1 as its input file. This program gets user input of a value from 1000 to 10000, and counts how many times the user's value appears in the input file. It reports to the user using screen output.

Here's the code that I have after several failed attempts:

#include <iostream>
#include <fstream>


using namespace std;

int count(int number, int input, int length)
{
int counter = 0;
for(int i = 0; i < length; i++)
if(input == number)
counter++;
return counter;
}

int main()
{
int num,input;

ifstream fin;
fin.open("ran_num.txt");
if(fin.fail())
{
cout<<"Input file opening failed."<<endl;
cin.get();
}

cout<<"Enter a number between 1000 to 10000:";
cin>>num;

fin>>input;

cout<<num<<"appears "<<count(num, input, 3000)<<" times in the file."<<endl;

return 0;
}


I'm completely lost and just need to figure out what I use to count a user inputer value. Any help is appreciated!

Edit
This is what I have now. My program can now read the whole file, but I still do not know how to count a user-inputted number.

#include <iostream>
#include <fstream>
#include <iomanip>


using namespace std;

int main()
{
ifstream fin("ran_num.txt");
int num, user_input;

cout<<"Enter a number between 1000 to 10000:";
cin>>user_input;

while(fin>>num)
{
if(num == user_input)
{
cout<<count++;
}
}
return 0;
}

Answer

Are you sure your program is opening the file? You should check if the file is opened correctly, you also should close the file after use. Also you're outputting count before incrementing it. I suggest changing your while loop this way:

if (fin.is_open())
{
    while (fin >> num)
    {
        if (num == user_input)
        {
            ++count;
        }
    }
    fin.close();
    cout << count;
}
else
{
    cout << "Unable to open file";
}