how to count a specific number from a file in c++ - 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;
}

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";
}

This is the correct code that I have. It works perfectly now thank you!
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream fin("ran_num.txt");
int num, user_input, count;
cout<<"Please enter a number from 1000 to 10000:";
cin>>user_input;
if (fin.is_open())
{
while (fin >> num)
{
if (num == user_input)
{
++count;
}
}
fin.close();
cout<<user_input<<" occurs "<<count<<" times.";
}
else
{
cout<<"Unable to open file.";
}
fin.close();
return 0;
}

Related

Is there a way i can use a text file to operate a program to display the occurrence of numbers in C++?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ticket ("numbers.txt");
bool isCovered[99];
int number;
for (int i = 0; i < 99; i++)
isCovered[number] = false;
// Read each number and mark its corresponding element covered
ticket >> number;
while (number != 0)
{
isCovered[number - 1] = true;
ticket >> number;
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
return 0;
I know i may have confused you all with the last question i posted but this time i understand the concepts and have an even better question. How can i display the number of occurrences using a txt file in fstream while using C++? And how would i properly use my for and if loops for said problem, thanks?
Update: Got the numbers from the text file to display as well as numbers 1 - 99. But how do i code for the number of occurrences?
#include <fstream>
#include <string>
using namespace std;
int main()
{
int i;
// Open the text file in the system
ifstream infile;
infile.open("numbers.txt");
if(infile.fail())
{
cout << "This file does not work";
}
else{
string s;
while(infile >> s){
cout << s << endl;
}
}
// Display all numbers 1 through 99
for (i = 1; i < 99; i++){
cout << i << endl;
}
}

C++ Why I can't use the loop: while(fin>>x) for twice

I have some question about file I/O in c++.
When I use while(fin>>x) for twice in my program and cout two times, only the first time will display on my screen.
And my test.txt is:
I like eat banana
I like eat apple
My code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(){
ifstream fin;
fin.open("test.txt");
if(fin.fail()){
cout<<"Error!"<<endl;
exit(1);
}
else{
int i=0,j=0;
string x,y,a[20],b[20];
while(fin>>x){
a[i]=x;
i++;
}
fin.
while(fin>>y){
b[j]=y;
j++;
}
for(int q=0;q<20;q++){
cout<<a[q]<<" ";
}
for(int w=0;w<20;w++){
cout<<b[w]<<" ";
}
}
fin.close();
return 0;
}
The reason making fin >> x return false (and exiting the first loop) still exists when you write fin >> y right afterwards. Hence, once fin >> x-loop is left, fin >> y-loop will not be entered.

How to save lines from a file into an array

I want to get lines from a .txt file and save it into an array. Then I want to display it in a for loop. Here is my code and I don't know what is wrong with it. My file is named quiz.
The program is running but it doesn't display array with lines.
#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main()
{
fstream quiz;
quiz.open("quiz.txt", ios::in);
if(quiz.good()==false)
{
cout<<"File does not exist"; exit(0);
}
string array[100000];
string one;
int counter=0;
while(getline(quiz,one))
{
one=array[counter];
counter++;
}
for(int i=0; i<=counter; i++)
{
cout<<array[i];
}
quiz.close();
return 0;
}

How to read file and put in an array

#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
string arr[3][2];
int i =0,j=0;
ofstream out ("test1.dat" , ios::app);
string name;
while(true)
{
cin>>name;
if(name=="end")
break;
out << name <<' ' ;
}
out.close();
ifstream in ("test1.dat", ios::in);
in >> name;
while(!in.eof())
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}
in.close();
for(i=0;i<3;i++){
cout<<endl;
for(j=0;j<2;j++){
cout<<arr[i][j]<<" ";}
}
return 0;
}
please help i have run-time error with this.what is my problem?i want to write some data in a file then read them and put them in an array and then print the array.i want to write and read the file by string not by character.sorry about my weak english.
thanks
Try adding a condition for i in your while loop.
This fixes your run-time error with the array bounds but you still have a logic error (unless you want duplicate occurrences of the same word in your array?)
while(!in.eof() && i < 3)
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}

Read a .txt file, calculate sum and mean

I have a .txt file which contains numbers and looks like this:
1
2
3
etc
The numbers are unimportant but they all start on a new line.
I want to then find the sum & mean of the numbers in the text file.
Here's what I have so far:
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
int sum(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
int x(0);
cout<<"numbers.txt";
cin>> file_name;
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin>>x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl;
fin>>x;
sum=sum+x;
sumcount++;
if(x%2==0)
even++;
else
odd++;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl;
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
The start loads the numbers but it won't execute the next step.
i have looked at a lot of other code and tried to implement other ideas to solve the problem; however, some people use loops and arrays and other things and I'm not sure which to use.
How can I get my program to find the sum and mean of numbers in the file?
also any other links for help would be appreciated
EDIT: although the numbers are intergers the mean may not be
Here is your working code.
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a = 0;
myfile >> a;
while (!myfile.fail())
{
printf("%f ", a);
myfile >> a; // here you dispay your numbers
}
getchar(); // waiting for input
float sum(0);
int x(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
cout<<"numbers.txt" << endl;
cin>> file_name; // waiting for enter file name
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin >> x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl; // display number again
sum=sum+x;
sumcount++;
if(x % 2==0) // compuing your file statistics
even++;
else
odd++;
fin>>x;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl; // displaying results
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
I have added some minimal alteration to make your program work correctly.
the result
and more
As soon as your main function encounters the statement return 0 it will exit the program and fail to execute the remaining code. This should generally appear only once in your main function, at the end of your code block
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n=0;
int sum=0,total=0;
fstream file("numbers.txt");
while(file >> n) // or while(cin >> n) to read from stdin, commandline
{
sum += n;
total++;
}
int average = (float) sum/total;
cout<<"sum: " << sum << endl;
cout << "average: " << average << endl;
return 0;
}
#include <iostream>
#include<fstream>
int main()
{
std::ifstream txtFile;
txtFile.open("data.txt");
//TODO: check if the file fails to open.
double tempNum, mean(0.0), sum(0.0), count(0.0);
while (txtFile >> tempNum)
{
sum += tempNum;
++count;
}
mean = sum/count;
std::cout << "mean: " << mean << " sum: " << sum << std::endl;
return 0;
}