average is outputting as inf - c++

I am trying to calculate the average for a class from scores given using a data file that was given.
The formula I'm using is grade_Average = sum / i;
The data file that was given is :
Joe Johnson 89
Susie Caldwell 67
Matt Baker 100
Alex Anderson 87
Perry Dixon 55
The output I am getting is
Johnson,Joe B
Caldwell,Susie D
Baker,Matt A
Anderson,Alex B
Dixon,Perry F
Class average inf
I am not sure if I have the formula wrong or if the formula is in the wrong place.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
// Variable declarations:
string fName[10];
string lName[10];
float grade_Average;
string file;
string name;
int scores[10];
float sum = 0;
char grade;
int i = 0;
ifstream din;
// Function body:
cout << "Enter the name of the file. " << endl;
cin >> file;
din.open(file.c_str());
if (!din)
{
cout << " Cannot open the input file. Please try again." << endl;
return 0;
}
cout << setw(10) << setfill(' ') << "Name" <<setw(20)<<setfill(' ')<< "Grade" << endl;
while (!din.eof())
{
din >> fName[i];
din >> lName[i];
din >> scores[i];
sum = sum + scores[i];
switch (static_cast<int> (scores[i]/10))
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break;
case 6:
grade = 'D';
break;
case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
grade = 'A';
break;
case 10:
grade = 'A';
break;
default:
cout << "Invalid score." << endl;
i++;
}
name = lName[i] + ',' + fName[i];
cout << setw(10) << setfill(' ') << name << setw(20) << setfill(' ')<<(" ") << grade << endl;
}
grade_Average = sum / i;
cout << "Class average " << grade_Average << endl;
din.close();
return 0;
}

Your i++ is inside the default block. The i variable is most probably 0. Either you put i++ outside of the switch block or you put it before every break statement.

i++ is inside the switch block and in the default case. It will never be executed for the given input. Therefore throughout the run i will just be 0. Dividing by 0 gives you inf.
Your program will also fail if more than 10 entries are given (and the first issue is corrected). You should use std::vector<std::string>, std::vector<int> and push_back instead of the raw arrays of std::string and int, if these arrays are needed at all. (For just calculating the average, the individual entries don't really need to be saved.)

Related

Guessing Game with functions c++

I am writing a guessing game program using functions for each thing, I keep getting errors saying function isn't set so when I try to call it, it isn't working. I can't figure out what I am doing wrong.
I know I have arguments for the functions that aren't being used but I cant seem to figure out where or how I should include those in the function themself.
I am fairly new to programming/c++ so please no negative comments I am just trying to get as much help as I can.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int getGuess(string prompt);
string getRank(int guessCount);
bool getPlayAgain(string prompt);
void playOneGame();
int main(){
srand(time(0));
int number = rand() % 100 + 1;
string prompt = getGuess();
do(
playOneGame();
)while(getPlayAgain())
return EXIT_SUCCESS;
}
int getGuess(string prompt){
int num;
int guessCount = 0;
prompt = cout << "Please enter a number between 1-100: ";
cin >> num;
if(num > 100){
cout << "Please enter a number between 1-100: " << endl;
}
if(num < 1){
cout << "Please enter a number between 1-100: " << endl;
}
if(num <= 100){
cout << "The number you guessed is: " << num << endl;
guessCount++;
}
}
string getRank(int guessCount){
switch(guessCount){
case 1:
case 2:
case 3: cout << "Lucky!" << endl;
break;
case 4:
case 5:
case 6: cout << "Awesome";
break;
case 7:
case 8:
case 9: cout << "Good";
break;
case 10:
case 11:
case 12: cout << "Meh";
break;
case 13:
case 14:
case 15: cout <<"Poor";
break;
default: cout << "Pathetic";
}
}
bool getPlayAgain(string prompt){
bool done = false;
int num1;
while(!done){
cout << "Enter 1 to play again or 2 to quit: ";
cin >> num1;
if(num1 == 2){
break;
}
else(
getGuess();
)
}
}
void playOneGame(){
getGuess();
getRank();
getPlayAgain();
}
No return statement in getguess() function but function signature is int return type.
Getguess() accepts prompt parameter as input but not used inside the function.

How to add char directly after (cin) in c++

I am trying to add a percent sign directly after a users input (so that the user doesn't have to type the percent symbol). When I try this, it either goes to the next line or doesn't work at all.
What I want: _%
// the blank is for the user's input.
Sorry if this is messy, I'm not sure how to add c++ here.
Here are some things that I have attempted:
// used a percent as a variable:
const char percent = '%';
cout << "Enter the tax rate: " << percent; // obviously here the percent
symbol goes before the number.
double taxRate = 0.0;
cin >> taxRate >> percent; // here I tried adding it into the cin after the cin.
cin >> taxRate >> '%'; // here I tried adding the char itself, but yet another failed attempt...
So, is it even possible to do what I am wanting?
It is definitely possible, however iostream does not really provide a proper interface to perform it. Typically achieving greater control over console io requires use of some platform-specific functions. On Windows with VS this could be done with _getch like this:
#include <iostream>
#include <string>
#include <conio.h>
#include <iso646.h>
int main()
{
::std::string accum{};
bool loop{true};
do
{
char const c{static_cast<char>(::_getch())};
switch(c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
// TODO limit accumullated chars count...
accum.push_back(c);
::std::cout << c << "%" "\b" << ::std::flush;
break;
}
case 'q':
{
loop = false;
accum.clear();
break;
}
case '\r': // Enter pressed
{
// TODO convert accumullated chars to number...
::std::cout << "\r" "Number set to " << accum << "%" "\r" "\n" << ::std::flush;
accum.clear();
break;
}
default: // Something else pressed.
{
loop = false;
accum.clear();
::std::cout << "\r" "oops!! " "\r" << ::std::flush;
break;
}
}
}
while(loop);
::std::cout << "done" << ::std::endl;
return(0);
}
I have been having the same prob but I found an alternative, it doesn't automatically put % sign but it can let you add the %sign right after the cin without messing up when you run the code :> this is my homework, hope it helps as an example:
enter image description here
and here's what the output looks like:enter image description here
//Program that computes the total amount of savings after being invested
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
char percent [1];
float IR, IRp, TC, P, I, A;
cout << "Investment Rate:" << setw(10) << left << "";
cin>> IR >> percent;
IRp = IR*.01;
cout << "Times Compounded: " <<setw(10)<<""; //TC
cin>> TC;
cout<<"Principal:" << setw(13) << right << "$"; //P
cin>> P;
A = P*(pow(1 + (IRp/TC), TC));
I=A-P;
cout<<"Interest: " <<setw(15)<<"$ " <<fixed<<setprecision(2)<<I<<endl;
cout<< "Amount in Savings:" <<setw(5)<<"$"<<fixed<<setprecision(2)<<A<<endl;
return 0;

How do I get a variable to print a string

My question is if there was a way to get an integer variable and then print a specific word when it is set.
What I mean is if someone inputs a value of 1 that is then assigned to variable int fCur, is there a way to print a word (for example Germany) instead of the value 1 ?
cout << "You selected "<< fCur << endl;
I want it to print
"You selected Germany"
not
"You selected 1"
I appologize if this is poorly worded this is my first time using this site
If you want to have each country indexed as follows:
Germany
India
Korea
you can simply use this:
#include <iostream>
#include <string>
int main()
{
std::string countries[] = {"Germany", "India", "Korea"};
int country_number;
std::cin >> country_number; // invalid input is not being checked
// array indexing starts from 0
std::cout << "You selected " << countries[country_number - 1] << std::endl;
return 0;
}
I suggest using an enum to represent the options, and to use if statements that will set the string value:
int main()
{
enum Country {GERMANY = 1, SPAIN = 2, ITALY = 3};
cout << "Enter an option: ";
int fCur{};
cin >> fCur;
string str;
if (fCur == GERMANY)
str = "Germany";
else if (fCur == SPAIN)
str = "Spain";
else if (fCur == ITALY)
str = "Italy";
else
;// Handle error
cout << "You selected " << str << endl;
}
As I guess it you want to create a menu for selecting options something like -
Germany
US
Spain
China
etc
If it is only integer 1 that is assigned to Germany then an if condition is enough else to display based on the selection from a menu use switch
int n;
cin >> n;
switch(n) {
case 1: {
cout << "Germany" << endl;
break;
}
case 2: {
cout << "US" << endl;
break;
}
case 3: {
cout << "Spain" << endl;
break;
}
case 4: {
cout << "China" << endl;
break;
}
default: cout << "Select from valid set of options";
}
Hope this helps.

Character in Switch-Statement C++

Please help! I can't produce the output of my program. This is the condition:
Construct a program that gives a discount of 100 pesos if the shirt bought is XL and the the price is greater than 500; and a discount of 50 pesos if the shirt bought is L and the price is greater than 600.
#include <iostream>
using namespace std;
int main()
{
int p;
int s;
cout << "Input price: ";
cin >> p;
cout << "Input size: ";
cin >> s;
switch (s)
{
case 'XL': case 'xl':
{
if (p>500){
cout << "Total price: " << p-100 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<500)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'L': case 'l':
{
if (p>600){
cout << "Total price: " << p-50 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<600)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'M': case 'm':
{
cout << "Total price: " << p << " pesos.";
break;
}
case 'S': case 's':
{
cout << "Total price: " << p << " pesos.";
break;
}
}
return 0;
}
The output of the program:
Input price: 500
Input size: XL
Process returned 0 (0x0) execution time : 5.750 s
Press any key to continue.
P.S. How can I remove the warning (multi-character character constant) in my program?
Thanks in advance!
If the size can be more than a single character, then you'll need to represent it with a string. You can't switch on a string, so you'll have to use if..else..else.. to deal with the value:
std::string size;
cin >> size;
if (size == "XL") {
// deal with size XL
} else if (size == "L") {
// deal with size L
} // and so on
If it were a single character, then you could use char (not int) to represent that:
char size;
cin >> size;
switch (size) {
case 'L':
// deal with size L
break;
// and so on
}
but for multiple characters, you'll need a string.
switch statement can handle int and char in C++. char data type can hold only one letter. Thus, if you input only one letter (X) for XL size will be fine ...
cout << "Input size (X/L/M/S): ";
cin >> s;
switch (s){
case 'X': case 'x':
You've declared s as an integer but attempt to use it as a character and character array. You should probably declare it is char s; and then use it consistently as just a single character -- which does mean that you can't check for XL. You could, however, just check for X in your switch.
If you absolutely must check for XL, then you'll need to use either a character array or std::string, although switch statements can only be used with single characters, so you may have to nest your switch to check for multiple characters or just use a series of if (strncmp(...)...) calls.

assignment switch case c ++

Requirements
VULTURE IS V, OWL IS O, EAGLE IS E...
A for loop to input the data each bird watcher has collected.
inside the for loop, a do ... while loop to input and process the data collected by one bird watcher.
inside the do ... while loop a switch statement is used to calculate the number of eggs for each type of bird. the default option, which does nothing, is used when an x is entered.
the do ... while loop is exited when an X is entered for the type of bird.
The totals part is fine as per code below
ok, now my problem is I can't seem to get through my switch case. It prompts me for the first watcher's info, when I enter it, it never moves over to the next watcher.
The input data given is
3
E2 O1 V2 E1 O3 X0
V2 V1 O1 E3 O2 E1 X0
V2 E1 X
And here is the code that I got so far:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int totNrVultureEggs, totNrEagleEggs, totNrOwlEggs, nrEggs,
nrVultureEggs, nrEagleEggs, nrOwlEggs, nrBirdWatchers, nrEggsEntered;
char bird;
// initialize grand totals for number of eggs for each type of bird
cout << "How many bird watchers took part in the study?";
cin >> nrBirdWatchers;
// loop over number of bird watchers
for (int i = 0; i < nrBirdWatchers ;i++ )
{
// initialize totals for number of eggs for each type of bird
// this bird watcher saw
nrVultureEggs = 0;
nrEagleEggs = 0;
nrOwlEggs = 0;
cout << "\nEnter data for bird watcher " << i + 1 << ":" << endl;
//loop over bird watchers
do{
cin >> bird >> nrEggs;
switch (bird)
{
case 'E':
case 'e':
nrEagleEggs = nrEagleEggs + nrEggs;
case 'O':
case 'o':
nrOwlEggs = nrOwlEggs + nrEggs;
case 'V':
case 'v':
nrVultureEggs = nrVultureEggs + nrEggs;
default :
nrBirdWatchers++;
break;
}
}while (i < nrBirdWatchers )
;
cout << "Bird watcher " << i + 1 << " saw " << nrVultureEggs;
cout << " vulture eggs, " << nrEagleEggs << " eagle eggs and ";
cout << nrOwlEggs << " owl eggs " << endl;
// increment grand totals for eggs
}
// display results
cout << "\nTotal number of vulture eggs: " << totNrVultureEggs;
cout << "\nTotal number of eagle eggs: " << totNrEagleEggs;
cout << "\nTotal number of owl eggs: " << totNrOwlEggs;
return 0;
}
You need a break after each switch case. Also, you need a boolean variable 'done' to tell you when a single birdwatcher is done.
bool done = false; //Flag to note when a birdwatcher is done
do {
string data;
cin >> data;
bird = data[0];
nrEggs = data[1]-0;
switch (bird)
{
case 'E':
case 'e':
nrEagleEggs = nrEagleEggs + nrEggs;
break; //was missing before
case 'O':
case 'o':
nrOwlEggs = nrOwlEggs + nrEggs;
break; //was missing before
case 'V':
case 'v':
nrVultureEggs = nrVultureEggs + nrEggs;
break; //was missing before
default :
done = true; //changed: No more birds to report
break;
}
}while (!done) //Check if there are birds to report
I rewrote the whole program, now it works, but take care of the input:
because of the type of the input, you have to give ALWAYS a couple of char-int, or you will have a bad time xD [The problem is in the buffer].
So the input would be:
3
E2 O1 V2 E1 O3 X0
V2 V1 O1 E3 O2 E1 X0
V2 E1 X0
The source below:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
bool done;
char birdType;
int eagleEggs, owlEggs, vultureEggs;
int totEagleEggs, totOwlEggs, totVultureEggs;
int eggsTemp, eggsIn, birdWatchers;
cout << "How many bird watchers took part in the study?";
cin >> birdWatchers;
totEagleEggs = totOwlEggs = totVultureEggs = 0;
for (int i = 0; i < birdWatchers ;i++ ){
eagleEggs = owlEggs = vultureEggs = 0;
done = false;
cout << endl;
cout << "Enter data for bird-watcher n. " << (i + 1) << ":" << endl;
do{
cin >> birdType >> eggsTemp;
switch (birdType)
{
case 'E':
case 'e':
eagleEggs += eggsTemp;
totEagleEggs += eagleEggs;
break;
case 'O':
case 'o':
owlEggs += eggsTemp;
totOwlEggs += owlEggs;
break;
case 'V':
case 'v':
vultureEggs += eggsTemp;
totVultureEggs += vultureEggs;
break;
default:
done = true;
}
}while (!done);
cout << "The bird-watcher n. " << (i + 1) << " saw " << vultureEggs;
cout << " vulture eggs, " << eagleEggs << " eagle eggs and ";
cout << owlEggs << " owl eggs." << endl;
}
cout << endl;
cout << "Total number of vulture eggs: " << totVultureEggs << endl;
cout << "Total number of eagle eggs: " << totEagleEggs << endl;
cout << "Total number of owl eggs: " << totOwlEggs << endl;
system("PAUSE");
return 0;
}