So this program calculates and prints the largest, smallest, average, and sum of the sequence a user enters. My only problem that I have found is that when a symbol is entered, it outputs it is wrong, but still ""adds" it's ascii code to the sum, messing up the results. Also, if someone else a number and letter such as 1361351P, it still reads it. Any help is appreciated.
/** C2.cpp
* Test #2 Problem C2
* Robert Uhde
* This program calculates and prints the largest, smallest, average,
* and sum of a sequence of numbers the user enters.
*/
#include <iostream>
using namespace std;
// Extreme constants to find min/max
const double MAX = 1.7976931348623157e+308;
const double MIN = 2.2250738585072014e-308;
// Create generic variable T for prototype
template <class T>
// Prototype dataSet that with request inputs and calculate sum, average, largest and smallest numbers.
T dataSet(T &sum, T &largest, T &smallest, T avg);
int main(){
// Intro to program
cout << "This program calculates and prints the largest, smallest,"
<< endl << "average, and sum of a sequence of numbers the user enters." << endl << endl;
// defined used variables in longest double format to include as many types as possible with largest range
double avg = 0, sum = 0, max, min;
// Call dataSet which returns avg and return references
avg = dataSet(sum, max, min, avg);
// Output four variables
cout << endl << "The largest of the sequence you entered is: " << max << endl;
cout << "The smallest of the sequence you entered is: " << min << endl;
cout << "The sum of the sequence you entered is: " << sum << endl;
cout << "The average of the sequence you entered is: " << avg << endl;
system("pause");
return 0;
}
// Create generic variable T for dataSet
template <class T>
T dataSet(T &sum, T &max, T &min, T avg){
T num;
min = MAX, max = MIN;
// count number of valid numbers
int count = 0;
// Repeat this loop until ^Z
do{
cout << "Enter a sequence of numbers: (^Z to quit) ";
cin >> num;
// if valid, then increment count by 1, add to sum, find out if it's new max or min
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double))){
count++;
if(num > max)
max = num;
sum += num;
if(num < min)
min = num;
}
// if user enters ^Z break out
else if(cin.eof())
break;
// If there is some sort of type error, print so and clear to request again
else{
cout << "Error. Try Again.\n";
cin.clear();
cin.ignore(80, '\n');
}
}while(true);
// Calculate average and then return
avg = sum / count;
return avg;
}
Your conditioning check needs some more work. I would use more specific condition checkings such as isalpha or isdigit which are part of the since these condition checks below are not good enough
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double)))
Best of luck!
Related
I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.
for example:
while(cin.fail()) {
cout << "Error" << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Please enter grade:"
std::cin >> grade;
}
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer
Write a program that first generates 100 random numbers in the range [11, 25] and store them in a file named “random.txt”. Write just one number in each row. Then open and read data from the file “random.txt”. Calculate the average of all the 100 number and count how many times the number 16 occurs. Using only one single loop in this step. That is, update the running total and the occurrence of 16 during each repetition of the loop. The sample file and output are given below.
Hint: To generate a random integer in a range [min,max, use the following statement
rand()%(max-min+1)+min;
>>Write a program that first generate 100 random numbers in the range [11, 25] and store them in a file named “random.txt”.
C++ provides the following classes to perform output and input of characters to/from files:
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
I suggest you could try to use ofstream to write the random numbers to “random.txt” file.
Here is the code:
cout << "Now writing data to the file." << endl;
ofstream OutFile("random.txt");
for (int i = 0; i < 100; i++)
OutFile << rand() % (25 - 11 + 1) + 11 << '\n';
OutFile.close();
cout << "Done with the writing." << endl;
>>Then open and read data from the file “random.txt”. Calculate the average of all the 100 number
We could use fopen_sto open the file. And then we can use fscanf_s to read formatted data from stream.
Here is the code:
cout << "Now reading deta fron the file." << endl;
int n, r;
double d, sum;
FILE *f;
fopen_s(&f,"random.txt", "r");
n = 0;
sum = 0.0;
while (1) {
r = fscanf_s(f, "%lf", &d);
if (1 == r)
{
sum += d;
n++;
}
else if (0 == r) {
fscanf_s(f, "%*c");
}
else break;
}
fclose(f);
cout << "average value=" << sum / n << endl;
>> count how many times the number 16 occurs
We could read numbers line by line, if the number is equal to "16", "sum1" plus "1".
Here is my code:
int sum1 = 0;
ifstream infile("random.txt");
int number;
infile >> number;
while (!infile.eof())
{
if (number == 16)
{
sum1++;
}
infile >> number;
}
cout << "The number 16 appears " << sum1 << " times in the file" << endl;
I am somewhat new to c++, our class only went over debugging briefly. This is probably my 10th do over, I have been over it a week, have done plenty of research over the web and I just don't understand debugging enough to figure out how to fix my code. The program is supposed to real a file like this:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
When it reads the file it's supposed to output the student ids, what they answered on each question and the grade for each student. My problem is, I don't know much about debugging and VS keeps throwing an exception at the end of the code I provided. I am just learning how to use dynamic arrays so I know it has something to do with my use of them because I had the program working fine in my other c++ class but I had to change it around to use dynamic arrays for this project.
What's wrong with my program? I have researched the web and reread the chapters in the book over and over and I cannot figure it out.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstddef>
using namespace std;
// function prototypes
void readFile(ifstream& inFile);
char assignGrade(int score, int numQues);
int main()
{
int numQues = 20;
int numStud = 0;
string *studentIDs;
studentIDs = new string[numStud];
char *correctAnswers;
correctAnswers = new char[numStud];
char *studentAnswers;
studentAnswers = new char[numQues];
ifstream inFile;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
cout << "\nPlease Enter the Number of Students: ";
cin >> numStud;
cout << endl;
readFile(inFile);
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the space between the student ID and the answer
for (int j = 0; j < numQues; j++) // loop questions
{
studentAnswers[j] = inFile.get(); // get the student's answers
}// end for
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer equals correct answer
score += 2; // correct answer
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ')
score -= 1; // incorrect answer but not a blank
else if (studentAnswers[j] == ' ')
score = 0;
delete[] studentAnswers;
}// end for
if (score < 0)
score = 0; // don't allow for negative scores
cout << endl; // new line, housekeeping
char grade = assignGrade(score, numQues); // call assignGrade function
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
delete[] studentIDs;
system("pause");
return(0);
}
void readFile(ifstream& inFile)
{
inFile.open("Ch12_Ex2Data.txt"); // use inFile to open Ch8_Ex6Data.txt
if (!inFile) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file and try again!\n" << endl; // display error message
system("pause");
exit(1); // exit the program
}
} // end readFile function
char assignGrade(int score, int numQues)
{
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
return 'A';
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
return 'B';
else if (percentScore >= 0.7) // if score is greater than or equal to 70%, return C
return 'C';
else if (percentScore >= 0.6) // if score is greater than or equal to 60%, return D
return 'D';
else // any score lower thn 60%, return F
return 'F';
} // end assignGrade function
It keeps breaking here in the debugger:
static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right)
_NOEXCEPT
{ // assign an element
_Left = _Right;
}
// Redo Programming Exercise Six of Chapter Eight
// Using Dynamic Arrays -- C++ Advanced
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototype
void readFile(ifstream& inFile, string fileName);
int main()
{
// variables, pointers and dynamic arrays
int numStud = 200; // stores the number of students, max students was 200
int numQues = 20; // stores the number of questions on test
string *studentIDs; // pointer variable for studentIDs dynamic array
char *correctAnswers; // pointer variable for correctAnswers dynamic array
correctAnswers = new char[numQues]; // correctAnswers dynamic char array
char *studentAnswers; // pointer variable for studentAnswers dynamic array
studentAnswers = new char[numQues]; // studentAnswers dynamic char array
char *fileName; // pointer variable for fileName dynamic char array
fileName = new char[25]; // fileName dynamic char array
ifstream inFile; // input stream variable inFile
// display message to explain the program
cout << "\nJames Flowers - Chapter 12 - Programming Exercise 2" << endl;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
// request file name for fileName dynamic char array
cout << "\nPlease Enter the File Name (Ch12_Ex2Data.txt): ";
cin >> fileName;
cout << endl;
// call readFile function to read the file
readFile(inFile, fileName);
// request number of students for studentIDs dynamic char array and some calculations
cout << "\nHow many students took this test? (4): ";
cin >> numStud;
cout << endl;
studentIDs = new string[numStud]; // create studentIDs dynamic char array
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the blank space
inFile.getline(studentAnswers, '/n'); // get the student's test answers
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer is correct
score += 2; // add 2 to score
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ') // incorrect answer but not blank
score -= 1; // subtract 1 from score
else if (studentAnswers[j] == ' ') // if question left blank
score -= 0; // nothing subtracted from score
studentAnswers[j] = ' '; // clear each indice for next student
}// end for
cout << endl; // new line, housekeeping
char grade = 0; // char variable grade initialized to 0
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
grade = 'A'; // grade = A
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
grade = 'B'; // grade = B
else if (percentScore >= 0.7) // if score is greater than or equal to 70%,
grade = 'C'; // grade = C
else if (percentScore >= 0.6) // if score is greater than or equal to 60%,
grade = 'D'; // grade = D
else // any score lower than 60%,
grade = 'F'; // grade = F
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
system("pause"); // pause for readability
return(0);
}// end main
// readFile function reads the file, if not displays error message
void readFile(ifstream& inFile, string fileName)
{
inFile.open(fileName); // use inFile to open input file
if (!inFile.is_open()) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file name and try again!\n" << endl; // display error message
system("pause"); // pause for readability
exit(1);
}// end if
} // end readFile function
I want to make a program where the user can input many numbers but the program will have to identify if the first four or five numbers is equal to the numbers I've set.
ex.
user inputs 0123456789
then if first 5 is equal to number I've set.
Like if ( 01234 = 02134). But all the numbers can be stored in a variable and be displayed again.
Is it possible? Thank you in advance.
this worked.
kind of.
My code is as follows:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
{
int mnum [11];
int ctr;
for (ctr=0; ctr<=10; ctr++)
{
cout << "Enter your mobile number: ";
cin >> mnum [ctr];
}
cout << "Your mobile number is ";
if (mnum [3] == 1||2 && mnum [4] == 3||1)
{
for (ctr=0; ctr<=10; ctr++)
{
cout << mnum [ctr];
}
}
else
{
cout << "Sorry. Invalid mobile number prefix." << endl;
system ("pause");
return main ();
}
return 0;
}
but i have to enter each number. how to make it entr it in one go and still have the same results?
You can use modulus and integer division together to get the individual digits.
Here's a mocked up example that will get each digit of a number and print it individually (notice the output number is reversed because of how I am getting the digits):
int num = 123456;
while(num > 0) {
std::cout << num % 10 << ' ';
num /= 10;
}
Output:
6 5 4 3 2 1
#include <iostream>
using namespace std;
int main ()
{
int size = 0;
int* myArray = new int [size + 1];
cout << "Enter the exponent of the first term: ";
cin >> size;
cout << endl;
for (int i = size; i >= 0; --i)
{
cout << "Enter the coefficient of the term with exponent "
<< i << ": ";
cin >> myArray[i];
}
for (int i = size; i >= 0; --i)
{
cout << i << endl;
}
return 0;
}
Why am I getting an assertion error on input greater than 2? This is the precursor to a polynomial program where the subscript of the array is the power of each term and the element at array[subscript] is the coefficient.
Your array is allocated to be an int[1]. It needs to be allocated after you read in the size value.
You are initializing your array when size = 0, giving an array size of 1
You get your assertion error when you go outside of the array bounds (1).
myArray always has size 0 + 1 = 1. i starts out at whatever the user inputted, and the first array access you make is myArray[i]. So, say the user inputs 5, your array has size 1 and you access myArray[5]. It will fail!
I would allocate the array AFTER you input size.