Printing unknown number from a file

Write your question here.
--
Q. "A restaurant distributes a form to his customers to get their feedback on the food quality and the services. The customers have to rate the restaurant by assigning a number between 0 and 100. The rates have been stored in a file named rates.txt. The restaurant manager wants to know the percentage of satisfied customers.
Write a C++ program to do the following:

-Read unknown number of customer rating (int) stored in the file rates.txt
-Count the number of customers with rating 0-100 (Do not count negative numbers or numbers greater than 100).
-Count the number of satisfied customers with rating in the range 60 – 100.
-Calculate and print a proper message of the percentage (float) of the satisfied customers."
---
How can this be solved? I tried using a while loop but it's repeating the last entered number nonstop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	int x, count=0, countall=0; 
	float  pct;
	ifstream input;
	ofstream output;
	
	input.open("rates.txt");
	
	while(x<=100 && x>=0)
	{
	input>>x;
    cout<<x<<endl;

    if(x>=60 && x<=100)
    count++;

    countall++;


	}
	cout<<"Number of customers between 0-100: "<<countall<<endl;

	cout<<"Number of satisfied customers: "<<count;
	pct= count / countall * 100;
	cout<<"percentage of the satisfied customers: "<<pct;
	
	return 0;
}
Last edited on
The problem is that you didn't initialzie x so it has a random value.
A better way to read the numbers is.
1
2
3
4
5
6
7
8
9
10
11
  ifstream input("your filename");
  if (!input)
  {
    cerr << "Error opening file...\n";
    return 1;
  }
  int x = 0; // always good to initialize variables
  while (input >> x)
  {
    // your logic
  }
You're testing x before you read it in from the file.

Start with the basic loop to just read the file of integers.
1
2
3
while ( input>>x ) {
  cout << "Read " << x << " from file" << endl;
}


When you're happy that works, then start to add your additional logic to the loop.
Don't add everything at once. The mantra is small steps, compile and test often.
How about now? is there any part I missed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	int x;
	float count=0, countall=0, pct; 
	
	ifstream input;
	
	input.open("rates.txt");
	
  while( input>>x ) {
  cout << "Read " << x << " from file" << endl;
  if(x<=100 && x>=0)
  countall++;
  if(x<=100 && x>=60)
  count++;
}

	cout<<"Number of customers between 0-100: "<<countall<<endl;

	cout<<"Number of satisfied customers: "<<count<<endl;
	pct= count / countall * 100;
	cout<<"percentage of the satisfied customers: "<<pct<<"%"<<endl;
	
	return 0;
}
Topic archived. No new replies allowed.