This is my code, I don’t really like it and I know it can be improved but I just don’t know how. How can I refactor this program in terms of the many std::cin and std::cout operations over each other on each line? Is there any STL library magic that can be done to improve this? Thanks.
#include <iostream>
#include <string>
int main() {
int grade;
std::cout << "Enter the grade you recieved: ";
std::cin >> grade;
std::cout << grade << "\n\n";
if (grade == 100) {
std::cout << "You got a perfect score!\n";
} else if (grade > 90 && grade < 100) {
std::cout << "You got an A\n";
}
if (grade == 100) {
std::cout << "Grade: A+";
} else if (grade > 90 && grade < 100) {
std::cout << "Grade : A";
} else if (grade > 80 && grade < 90) {
std::cout << "Grade: B";
} else if (grade > 70 && grade < 80) {
std::cout << "Grade: C";
} else if (grade > 60 && grade < 70) {
std::cout << "Grade: D";
} else if (grade < 60) {
std::cout << "Grade: F";
}
}
To make it clear, I’m wanting to improve this code because it seems very un-idiomaitc to use all these if statements and print functions. How can I take advantage of the STL or template functions/classes to refactor this? C++11 is also welcome. Thanks.
Is one way to go to clean up stuff. Basically move all the
ifs into the GetGrade function and callcoutonce.Once inside GetGrade, you can use an array of the below and do away with the
ifs in favour of a loop.