Добрый день, я хотел бы предисловие, говоря, что это мой первый семестр работы с C ++, поэтому я прошу прощения, если ответы на ошибки, с которыми я столкнулся, очевидны / просты для ответа.
Я пытаюсь реализовать программу, которая запрашивает файл от пользователя, который содержит диапазон оценок от студентов (всего 20).Программа запрашивает ввод значений диапазона для традиционных буквенных оценок (т. Е. A = 90-100, B = 80-89, C = 70-79 и т. Д. До F), а затем подсчитывает количество оценок во входном файле пользователя.предоставлено.
На данный момент моя программа просматривает каждую буквенную оценку, чтобы получить диапазон оценок от пользователя, но у меня возникают проблемы с подсчетом количества оценок в файле.Он продолжает выводить «количество оценок в этом диапазоне составляет 29».
(Примечание: мой код также создает гистограмму, основанную на подсчете числа каждого класса в файле. Очевидно, что вывод моей гистограммы выглядитсупер удар на данный момент, потому что моя функция подсчета нуждается в некотором исправлении.)
Снова, извиняюсь, если ответ на это прост.Я очень новичок в этом и учусь на ходу.Спасибо за прочтение.
#include "SFML/Graphics.hpp"
#include <iostream>
#include <fstream>
#include <string>
const float WIDTH = 550.0; // width of the window for display
const float HEIGHT = 750.0; // height of the window for display
const int FONT_SIZE = 25; // character size
const float LEFT_X = 100.0; // Left X position for label
const float LOW_Y = 700.0; // LOW Y position for label
const float HIGH_Y = 50.0; // HIGH Y position for label
using namespace std;
void readConfig() {
int numGrades = 5;
int maxInGrade = 20;
string filename;
cout << "Enter the number of possible different grades: " << endl;
cin >> numGrades;
cout << "Enter the maximum number of students receiving the same letter grade: " << endl;
cin >> maxInGrade;
cout << "Enter the filename containing the scores: " << endl;
cin >> filename;
}
void initFrequency() {
string letters;
int numGrades = 5;
int freqLetters, low, high;
//below defines the lowest range for each grade
int grade_range_a = 90;
int grade_range_b = 80;
int grade_range_c = 70;
int grade_range_d = 60;
int grade_range_f = 0;
cout << "For each grade enter the" << endl << endl
<< "(1) string representing the grade," << endl
<< "(2) lowest possible score in that range, and" << endl
<< "(3) highest possible score in that range." << endl;
ifstream infile("/Users/quinntortellini/CLionProjects/cop3014-p7-f18/cop3014-p8-f18-attempt2/resources/hist.in");
if(!infile)
{
cout << "Can't open file hist.in";
exit(EXIT_FAILURE);
}
int sum=0, number;
for (int i=0; i<numGrades; i++)
{
cout << "Grade string: " << endl;
cin >> letters;
cout << "Lowest possible score: " << endl;
cin >> low;
cout << "Highest possible score: " << endl;
cin >> high;
cout << "The number of grades in this range is " << endl;
while (infile >> low)
{
if (low == grade_range_a||grade_range_b||grade_range_c||grade_range_d||grade_range_f);
counter = counter += 1;
}
{
cout << counter << endl;
}
infile.close();
}
}
int main() {
int numGrades = 5; // number of different letter grades
int maxInGrade = 20; // maximum number of students in any letter grade
string filename; // name of input file containing scores
//
// implementing readConfig, initializes numGrades, maxInGrade, and
// filename
//
readConfig();
string letters[numGrades]; // each entry represents string representing the grade
int freqLetters[numGrades]; // each entry records occurrence of grades corresponding
// to the letter grade
initFrequency();
//
//
//
sf::RenderWindow window(sf::VideoMode(600, 800), "COP3014 Grade Histogram");
sf::Font font;
font.loadFromFile("resources/arial.ttf");
// You are free to change the following code. However, as it is, it should work
sf::Text min, max;
min.setFillColor(sf::Color::Yellow);
min.setFont(font);
min.setString("0");
min.setCharacterSize(FONT_SIZE);
max.setFillColor(sf::Color::Yellow);
max.setFont(font);
max.setString(to_string(maxInGrade));
max.setCharacterSize(FONT_SIZE);
min.setPosition(LEFT_X-FONT_SIZE*2, LOW_Y-FONT_SIZE);
max.setPosition(LEFT_X-FONT_SIZE*2, HIGH_Y-FONT_SIZE/2);
sf::RectangleShape bars[numGrades];
sf::Text labels[numGrades];
float x_incr = (WIDTH - 100)/numGrades;
float x_offset = LEFT_X+FONT_SIZE;
float height_unit_pixels = (HEIGHT - (HIGH_Y + FONT_SIZE)) / maxInGrade;
int count = 0;
for (int i=0; i < numGrades; i++) {
float height = freqLetters[i] > maxInGrade ? maxInGrade : freqLetters[i];
bars[i].setSize(sf::Vector2f(x_incr-50, height*height_unit_pixels));
bars[i].setPosition(x_offset+x_incr/2, LOW_Y);
bars[i].rotate(180);
labels[i].setFillColor(sf::Color::Yellow);
labels[i].setFont(font);
labels[i].setString(letters[i]);
labels[i].setCharacterSize(FONT_SIZE);
labels[i].setFillColor(sf::Color::Red);
labels[i].setPosition(bars[i].getPosition().x-FONT_SIZE, LOW_Y+FONT_SIZE);
x_offset += x_incr;
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
default:
window.clear();
window.draw(min);
window.draw(max);
for (int i = 0; i < numGrades; i++) {
window.draw(bars[i]);
window.draw(labels[i]);
}
window.display();
}
}
}
return 0;
}