My topic may be confusing, this is my code in C++,how can i display the summary of number of student count for each Grade at the end of the program,can any body help in this?
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
This is the output i want,can anybody helP?
This is my actual output
[Output of the program][1]
edit: thanks for the responses, since im currently taking a required programming class, and while ive had literally 100% of the material before, I had it all in C++, so im not very good with the syntax yet, and we are told only with functions/loops/methods that have been discussed in lecture , looks like i still need to put more effort into it.
I'm not sure if I understand the problem correctly, but you could increment specified counters each time you determined the grade in your if-else-cascade and then std::cout the results after the while loop.
You could try what Wum suggested, so the code might look like this:
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
ifstream in;
ofstream out;
string name;
char grade;
double asg1, asg2, test, quiz, exam, coursework, overallScore, numbergrade;
int numStudentsA = 0;
int numStudentsB = 0;
int numStudentsC = 0;
int numStudentsD = 0;
int numStudentsF = 0;
in.open("Student.txt");
out.open("Result.txt");
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
//to keep reading the data in input file
while (!in.eof()) {
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 ) {
grade = 'A';
numStudentsA++;
}
else if (overallScore >= 60) {
grade = 'B';
numStudentsB++;
}
else if (overallScore >= 50) {
grade = 'C';
numStudentsC++;
}
else if (overallScore >= 40) {
grade = 'D';
numStudentsD++;
}
else if (overallScore >= 0) {
grade = 'F';
numStudentsF++;
}// grade
out << left << setw(15) << name ;
out << left << setw(3) <<coursework ; //coursework
out << left << setw(3) << exam ; //exam
out << left << setw(4) << overallScore ; //overall score
out << grade ;
out << endl;
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
}
cout << "Result Summary Date: " << date << endl;
cout << "Subeject: Programming Methodology" << endl;
cout << "Grade" << setw(10) << "Student" << endl;
cout << "A" << setw(10) << numStudentsA << endl;
cout << "B" << setw(10) << numStudentsB << endl;
cout << "C" << setw(10) << numStudentsC << endl;
cout << "D" << setw(10) << numStudentsD << endl;
cout << "F" << setw(10) << numStudentsF << endl;
cout << "Total Student = 10" << endl;
return 0;
}
I applied a bit of indentation to your code, try to use a single coding style. Also, you should read why the use of eof() is not recommended.
use a array to count the number of students for each grade and print out the array at the end.[ look for inline comments ]
Using a enum to index into the array for easy readability.
Instead of an array you could use maps was one of the suggestions .
eof in the above case is fine as , The first read is outside the while loop and then the check is done at the start. Also the subsequent reads are at the end of the while so the program will loop back right after the read to check the eof conditions and exit (without processing an empty buffer).
The code below checks for while (in>>name>>asg1>>asg2>>test>>quiz>>exam)
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
enum { GRADE_A = 0 , GRADE_B = 1, GRADE_C = 2 , GRADE_D = 3 ,GRADE_F = 4}; // use an enum to index into the array for each grade
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
_strdate(date);
ifstream in;
ofstream out;
int grades[5]; // to store the grades count
string name;
char grade;
double asg1,asg2,test,quiz,exam,coursework,overallScore,numbergrade;
in.open("Student.txt");
out.open("Result.txt");
grades[GRADE_A] = 0 ; grades[GRADE_B] = 0 ; grades[GRADE_C] = 0 ; grades[GRADE_D] = 0 ; grades[GRADE_F] = 0 ; // initialize array
while (in>>name>>asg1>>asg2>>test>>quiz>>exam) //to keep reading the data in input file
{
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 )
{grade = 'A' ;grades[GRADE_A]++;} // increment count for each grade
else if (overallScore >= 60)
{grade = 'B' ;grades[GRADE_B]++;}
else if (overallScore >= 50)
{grade = 'C' ;grades[GRADE_C]++;}
else if (overallScore >= 40)
{grade = 'D' ;grades[GRADE_D]++;}
else if (overallScore >= 0)
{grade = 'F' ;grades[GRADE_F]++;}; // grade
out<< left << setw(15) << name ;
out<< left << setw(3) <<coursework ; //coursework
out<< left << setw(3) << exam ; //exam
out<< left << setw(4) << overallScore ; //overall score
out<< grade ;
out<< endl;
}
cout<<"Result Summary Date: " << date << endl;
cout<<"Subeject: Programming Methodology"<<endl;
cout<< "Grade"<< setw(10) << "Student" <<endl;
cout<< "A" <<setw(10)<<grades[GRADE_A]<<endl; // output grade count
cout<< "B" <<setw(10)<<grades[GRADE_B]<<endl;
cout<< "C" <<setw(10)<<grades[GRADE_C]<<endl;
cout<< "D" <<setw(10)<<grades[GRADE_D]<<endl;
cout<< "F" <<setw(10)<<grades[GRADE_F]<<endl;
cout<<setw(0)<<endl;
cout<<"Total Student = 10"<<endl;
//At the end of the program, display the summary of number of student count for each Grade
Related
This question already has answers here:
Why is cout printing twice when I use getline?
(2 answers)
Closed 5 years ago.
When I run this and after I select my number as a player, Computer returns me two outputs (instead of one...). I have no idea why, could you please help me explain why that happens?
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int random(int a, int b)
{
int num = a + rand() % (b + 1 - a);
return num;
}
int main()
{
srand(time(NULL));
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
int min = 1;
int max = 100;
int comp;
string player;
while(1) {
comp = random(min, max);
cout << "Computer: " << comp << endl; // why does this get called twice??
getline(cin, player);
if (player == "too high") {
max = comp - 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "too low") {
min = comp + 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "correct") {
cout << "Computer found the number..." << endl;
break;
}
}
}
It's because you are mixing input using >> and getline. getline reads to the next newline, >> does not. After you have entered your number, there is still a newline left behind, you have typed it, but hasn't yet been read. The first time you call getline that left behind newline gets read, and the program doesn't pause. Only on the second time that you call getline does your program pause and wait for you to type something.
Simple way to fix the problem is
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
// flush pending newline
string dummy;
getline(cin, dummy);
I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}
Attempting a basic C++ challenge, (beginner at C++) and I produced this code. I understand that calling a value in an array starts from zero but I wanted the user to type from 1-5 instead of 0-4 because I didn't want to go the easy route and wanted to see if I could do it.
Here is my problem, I made a basic function to subtract 1 from the int choice to allow the user to enter 1-5 but the array see the value as 1-4. However as shown in this image it seems to ignore my function and skip to the next part of the code. I have included my code below.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string drink[5] = { "Coke", "Water", "Sprite", "Monster", "Diet Coke" };
int choice;
int correct = 0;
void AdjArray()
{
choice--;
};
int main()
{
while (correct != 1)
{
cout << "Enter the number of the beverage you would like." << endl;
cout
<< " Coke = 1\n Water = 2\n Sprite = 3\n Monster = 4\n Diet Coke = 5"
<< endl;
cin >> choice;
AdjArray;
if (choice >= 0 && choice <= 4)
{
cout << "You have chosen " << drink[choice] << "." << endl;
correct = 1;
}
else
{
system("cls");
cout << "Error, you entered: " << choice
<< ". Please enter a number between 1 and 5.\n" << endl;
}
}
return 0;
}
You're not calling your function. Change AdjArray; to AdjArray();
I've been working on a program recently that takes names as inputs and will eventually sort & binary search them. However upon attempting to make the array a dynamic size (that would increase by one with each loop iteration), it ran into various issues.
I can make the string array composed of 20 elements and the program works, but the extra credit for my assignment is to make it a dynamic size. Currently the program crashes without any sort of error code once it reaches "getline(cin, Names[x]);". I've been searching around and I know it'd be easier to do a vector instead of an array in this case, however I don't believe I'm allowed to use vectors on this assignment.
Thanks
Original Code
using namespace std;
#include <iostream>
#include <string>
void main()
{
int x = 0;
string * Names = new string[x];
bool NameInputEnd(0);
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << x << endl;
cout << "\n< Name " << (x + 1) << " > = ";
!!**CRASHES HERE**!!
getline(cin, Names[x]);
if (Names[x].empty() || x == 19)
{
cout << "\nFinal Name Amount = " << (x + 1) << endl << endl;
NameInputEnd = 1;
continue;
}
x++;
} while (NameInputEnd == 0);
delete [] Names;
}
Changes
int tempsize(1), x(0);
string * Names = new string[tempsize];
...
do
{
...
x++;
tempsize++;
}while (NameInputEnd == 0);
An array cannot be resized once it has been created. You have to destroy it and create a new array with a copy of the existing data. For example:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void main()
{
int x = 0;
int capacity = 20;
string * Names = new string[capacity];
string Name;
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << x << endl;
cout << "\n< Name " << (x + 1) << " > = ";
if ((!getline(cin, Name)) || Name.empty())
break;
if (x == capacity)
{
int newCapacity = capacity + 20;
string *newNames = new string[newCapacity];
copy(Names, Names + x, newNames);
delete [] Names;
Names = newNames;
capacity = newCapacity;
}
Names[x] = Name;
++x;
}
while (true);
cout << "\nFinal Name Amount = " << x << endl << endl;
delete [] Names;
}
You really should use a std::vector, though:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
vector<string> Names;
string Name;
Names.reserve(20); // optional
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << Names.size() << endl;
cout << "\n< Name " << (Names.size() + 1) << " > = ";
if ((!getline(cin, Name)) || Name.empty())
break;
Names.push_back(Name);
}
while (true);
cout << "\nFinal Name Amount = " << Names.size() << endl << endl;
}
The program works all the way up until it checks for the name the user enters. When you enter the name you wish to search for in the array of structures that have been imported from a file full of customer info) it comes back segmentation fault core dumped. This puzzles me.
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
char name[50];
string email;
long int phone;
string address;
};
#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];
void readIn(ifstream& file){
int i=0;
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
}
void getAccount(){
char userPick[50];
char streamName[50];
cout << " What account will we be using? " << endl;
cin.getline(streamName, 50);
for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
}
}
}
int main(){
ifstream file;
file.open("2.dat"); //opens data account records text
readIn(file);
getAccount();
delete account;
return 0;
}
Your loop keeps reading everything into the initial element of the array:
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
because the value of i is never incremented. You can convert this to a for loop, like this:
for (count = 0 ; count < MAX && !file.eof() ; count++) {
file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}
Note that I changed i to count:
AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;
This will help you solve another problem - determining when the array ends in the getAccount function. Currently, you assume that the record is always there, so the outer loop keeps going on. Now that you have count, you could change the loop like this:
for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
break;
}
}
if (i == count) {
cout << "Not found." << endl;
}