I'll preface this by noting that I'm very new to C++ and programming in general so if I'm doing something improperly or writing code in an odd way, it's because i've only learned so much so far.
Anyways, I was given an assignment to write a program that first
Reads integers from a file of the user's choice
Outputs the sum and average of all the numbers greater than or equal to zero ,
Outputs the sum and average of all the numbers less than zero
Outputs the sum and average of all the numbers, whether positive, negative, or zero.
Then finally asks the user if they'd like to choose another file to run on again
The only catch is that I have to use a dynamic array within the code, I'm assuming in order to allow the file to hold any amount of integers.
So far, I have everything except for the implementation of the dynamic array. The code is currently programmed to only accept 10 integers (as there are no arrays in the code yet).
Here's my code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
//Variables
string inFile;
int numbers, i = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double count = 0, neg_count = 0, pos_count = 0;
char answer;
do
{
//Input Question
cout << "Enter the file name.\n";
cin >> inFile; // Input from User
ifstream fin; // Open File
fin.open(inFile);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
while (count < 10)
{
fin >> numbers;
if (numbers >= i)
{
sum += numbers;
count += 1;
pos_count += 1;
}
if (numbers < i)
{
neg_sum = neg_sum + numbers;
count = count + 1;
neg_count = neg_count + 1;
}
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / 10.0;
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
Any help would be greatly appreciated!
Thanks in advance
UPDATE:
I've gotten this far but when I compile, the program runs continuously.Not sure what I'm doing wrong.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
//Variables
string file;
int i = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double neg_count = 0, pos_count = 0, totcount = 0;
char answer;
//Input Question
do
{
cout << "Enter the file name.\n";
cin >> file; // Input from User
ifstream fin; // Open File
fin.open(file);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
while (!fin.eof())
{
int numbers;
fin >> numbers;
int *dynamicArray;
dynamicArray = new int[numbers];
if (numbers >= i)
{
sum += numbers;
pos_count += 1;
totcount += 1;
}
if (numbers < i)
{
neg_sum = neg_sum + numbers;
neg_count = neg_count + 1;
totcount += 1;
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / totcount;
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
delete [] dynamicArray;
}
fin.close();
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
UPDATE:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
//Variables
string file;
int i = 0, value = 0, e = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double neg_count = 0, pos_count = 0, totcount = 0;
char answer;
//Input Question
do
{
cout << "Enter the file name.\n";
cin >> file; // Input from User
ifstream fin; // Open File
fin.open(file);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
// <---------- This works to get the size of the file
int elements;
vector<int> eCount;
while (fin >> elements)
{
eCount.push_back(elements);
}
int size = static_cast<int> (eCount.size());
cout << "size = " << size << endl;// <-----------Test to see if working
//From this point, size of the file is held in the variable, 'size'.
int array_size = size;
int* p;
p = new int[array_size];
int location = 0;
while (!fin.eof())
{
fin >> p[location];
location++;
}
cout << "P[12] is equal to " << p[12] << endl;// <----Test to see if array is initialized
while (fin >> p[location])
{
if (p[e] >= i)
{
sum = sum + p[location];
pos_count = pos_count + 1;
totcount = totcount + 1;
}
else
{
neg_sum = neg_sum + p[location];
neg_count = neg_count + 1;
totcount = totcount + 1;
}
location++;
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / totcount;
fin.close();
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
Thank you to everyone who's pitched in. I wish I didn't have to use a dynamic array but unfortunately I won't receive if I don't implement one. I updated my code but I can't seem to get the array working properly as it does not seem to load the input from the file properly. Anything helps!
Well, the biggest I/O problem you have is attempting to read with while (!fin.eof()). See Why !.eof() inside a loop condition is always wrong.. The biggest logic problem you are having is including the //Calculations in the same loop you are reading your integers from your file.
Since you read and integer and are keeping a running sum of the positive and negative values, there is no need for a dynamic array at all. You are currently keeping pos_count, neg_count, and totcount which are all you need to compute the respective averages when you leave your read loop.
To tidy things up a bit, let's look at your variables. While you can use double for pos_count, neg_count, and totcount, it's better to use an unsigned type for a counter. C++ provides size_t as a preferred sizetype for counts and lengths, but it's not mandatory -- it just makes sense. While you can use a separate file and answer, it is better to read each input into a std::string to ensure a single keystroke (like the user typing "Yes" instead of 'Y') doesn't leave additional characters unread in stdin. You can also use the same std::string for both your file and answer and just check the if the first character is 'y' or 'Y' to control your read another file loop.
Putting that together, your variables could simple be:
int main (void) {
std::string buffer; /* use single buffer for filename & answer */
do
{ // Variables (will be reinitialized for each file)
int number; /* you are reading one number at a time */
size_t neg_count = 0, pos_count = 0, totcount = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0., neg_sum = 0.;
(note: buffer to read the answer into is the only variable that must be declared before your do {...} while(); loop to be used as the test condition at the end)
If you remember nothing else, remember to validate every input, e.g.
std::cout << "Enter the file name: ";
if (!(std::cin >> buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
While you can check if the .fail() bit is set on the stream, a more general test is if the file stream goodbit is not set, e.g.
std::ifstream fin(buffer); // open file stream
if (!fin.good()) { // Check to see if file opens properly
std::cerr << "error: file open failed - " << buffer << ".\n";
return 1;
}
(note: either way will work)
When you read in a loop, condition your loop on a successful read. Your read loop here needs to be nothing more than:
while (fin >> number) { /* control read loop with read itself */
if (number >= 0) { /* handle positive numbers */
sum += number;
pos_count += 1;
}
else { /* if it's not >= 0, it's negative */
neg_sum = neg_sum + number;
neg_count = neg_count + 1;
}
totcount += 1; /* total count incremented each time */
}
fin.close();
That will capture all the information you need from your file. Now do the average calculations, but what happens if pos_count, neg_count, or totcount == 0. Dividing by zero is generally a really, really bad thing. Always validate your denominator, e.g.
// Calculations
if (pos_count > 0)
avg = sum / pos_count;
else
avg = 0;
if (neg_count > 0)
neg_avg = neg_sum / neg_count;
else
neg_avg = 0;
total_sum = sum + neg_sum;
if (totcount > 0)
total_avg = total_sum / totcount;
else
total_avg = 0;
Now for your output. How many times do you want to call cout for one continual block of output? (hint: once)
//OUTPUT (you only need one std::cout)
std::cout << "\nThe sum of all positive numbers is: "
<< sum << std::endl
<< "The average of all positive numbers is: "
<< std::setprecision(3) << avg << std::endl
<< "The sum of all negative numbers is: "
<< neg_sum << std::endl
<< "The average of all negative numbers is: "
<< std::setprecision(3) << neg_avg << std::endl
<< "The sum of all numbers is: " << total_sum << std::endl
<< "The average of all numbers is: " << std::setprecision(3)
<< total_avg << std::endl
<< "-------------------------------------------------\n\n"
<< "Want to read another file?\n"
<< "Enter 'Y' or 'y' for yes, any other character for no.\n";
That handles all your output needs in a single call (including your prompt for 'Y' or 'y'). Now just use the same std::string to take input on whether to continue or not, e.g.
if (!(std::cin >> buffer)) {
std::cerr << "(user canceled input)\n";
return 1;
}
/* condition on 1st char in buffer */
} while ((buffer.at(0) == 'y') || (buffer.at(0) == 'Y'));
}
That's it you are done. Putting it altogether, and replacing the fragile use of std::cin >> buffer with getline (std::cin, buffer) you would have:
#include <iostream>
#include <fstream>
#include <iomanip>
int main (void) {
std::string buffer; /* use single buffer for filename & answer */
do
{ // Variables (will be reinitialized for each file)
int number; /* you are reading one number at a time */
size_t neg_count = 0, pos_count = 0, totcount = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0., neg_sum = 0.;
std::cout << "Enter the file name: ";
if (!getline(std::cin, buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
std::ifstream fin(buffer); // open file stream
if (!fin.good()) { // Check to see if file opens properly
std::cerr << "error: file open failed - " << buffer << ".\n";
return 1;
}
while (fin >> number) { /* control read loop with read itself */
if (number >= 0) { /* handle positive numbers */
sum += number;
pos_count += 1;
}
else { /* if it's not >= 0, it's negative */
neg_sum = neg_sum + number;
neg_count = neg_count + 1;
}
totcount += 1; /* total count incremented each time */
}
fin.close();
// Calculations
if (pos_count > 0)
avg = sum / pos_count;
else
avg = 0;
if (neg_count > 0)
neg_avg = neg_sum / neg_count;
else
neg_avg = 0;
total_sum = sum + neg_sum;
if (totcount > 0)
total_avg = total_sum / totcount;
else
total_avg = 0;
//OUTPUT (you only need one std::cout)
std::cout << "\nThe sum of all positive numbers is: "
<< sum << std::endl
<< "The average of all positive numbers is: "
<< std::setprecision(3) << avg << std::endl
<< "The sum of all negative numbers is: "
<< neg_sum << std::endl
<< "The average of all negative numbers is: "
<< std::setprecision(3) << neg_avg << std::endl
<< "The sum of all numbers is: " << total_sum << std::endl
<< "The average of all numbers is: " << std::setprecision(3)
<< total_avg << std::endl
<< "-------------------------------------------------\n\n"
<< "Want to read another file?\n"
<< "Enter 'Y' or 'y' for yes, any other character for no.\n";
if (!getline(std::cin, buffer)) {
std::cerr << "(user canceled input)\n";
return 1;
}
/* condition on 1st char in buffer */
} while ((buffer.at(0) == 'y') || (buffer.at(0) == 'Y'));
}
(note: getline (std::cin, buffer) has been used in the code above to make the user input a bit more robust -- see the the section below the example output for the reasons)
Example Use/Output
Testing with three files, the first a 50x5 set of positive integers, then next a set of 10 integers with one negative value (-2213) and the last a file of 100 mixed positive and negative values would give:
$ ./bin/pos_neg_total
Enter the file name: dat/50x5.txt
The sum of all positive numbers is: 122180
The average of all positive numbers is: 489
The sum of all negative numbers is: 0
The average of all negative numbers is: 0
The sum of all numbers is: 1.22e+05
The average of all numbers is: 489
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
y
Enter the file name: ../../..//src-c/tmp/dat/10int_nl.txt
The sum of all positive numbers is: 2.03e+05
The average of all positive numbers is: 786
The sum of all negative numbers is: -2.21e+03
The average of all negative numbers is: -2.21e+03
The sum of all numbers is: 2.01e+05
The average of all numbers is: 774
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
Y
Enter the file name: ../../../src-c/tmp/dat/100int.txt
The sum of all positive numbers is: 1.93e+06
The average of all positive numbers is: 5.55e+03
The sum of all negative numbers is: -2.29e+05
The average of all negative numbers is: -1.76e+04
The sum of all numbers is: 1.7e+06
The average of all numbers is: 4.71e+03
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
n
There are many, many ways to put this together, and you are free to use as many variables or calls to std::cout as you like, but hopefully this will help you think further along the lines of "What does my program require?".
Using >> for User-Input is Fragile
As a final note, know that using std::cin >> string for user-input is horribly fragile as any whitespace the user types as part of the input will not be read (and it will be left unread in stdin. It is far better to use getline which will read the complete line into your string. Don't mix using the >> iostream for input with getline without accounting for any '\n' that may be left in stdin. You can then use std::cin.ignore() to clear. In your case it would simply be more robust to take all user input with getline, e.g.
if (!getline(std::cin, buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
Then filenames with whtespace would be properly handled, and if the user wanted to type "Yes I want to enter another file!" as his answer to your continue question, that would pose no problem at all. If you haven't got there yet in your class, put it in your hip-pocket. For an experiment, try replacing both user inputs with what is shown above with your original std::cin >> buffer and see what happens if you type "Yes I want to enter another file!" at the prompt :)
Let me know if you have further questions.
So why you need a vector(dynamic array) to store the integers since your code can handle the all cases by add a "break" expression on the condition of EOF.
If you really need it, below is what you need:
#include<vector>
vector<int> my_vec;
Related
I am trying to allow the user to select which file to open then use either a sentinel value or counter control to get all the values from the selected file. The code I have just outputs:
There are 0 values in the file.
The values in the file are: -1206517578
The average is -inf
Which is not true as there are 10 numbers in each file and they are all less than 9. I have been staring at this and can't figure out what is wrong.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
char fileSel;
double numValues = 0; //# of values in list
int values; //numbers in list
double avg = values / numValues;
int counter = 10;
const int SENTINAL_VALUE = -9999;
//Which file would you like to open?
cout << "Which file would you like to open?" << endl;
//1. Counter Controlled
cout << "1. Counter Controlled" << endl;
//2. Sentinel Controlled
cout << "2. Sentinel Controlled" << endl;
//Input file
cin >> fileSel;
//loop file selected
//counter controlled
while (fileSel == 1){
//open and check file
ifstream inFile;
inFile.open("counter_controlled.txt ");
if (inFile.fail()) {
cerr << "Could not open input file" << endl;
return -1;
}
while (numValues <= counter) {
inFile >> values;
numValues += 1;
}
inFile.close();
}
//sentinal
while ( fileSel == 2) {
//open and check file
ifstream inFile;
inFile.open("sentinel_controlled.txt");
if (inFile.fail()) {
cerr << "Could not open input file" << endl;
return -1;
}
//get values until
while (inFile >> values);
numValues += 1;
if (values == SENTINAL_VALUE){
cout << "There are " << numValues << " values in the file." << endl;
cout << "The values in the file are: " << values << endl;
//The average is 4.93.
cout << "The average is " << avg << endl;
}
inFile.close();
}
//The values in the file are:
cout << "There are " << numValues << " values in the file." << endl;
cout << "The values in the file are: " << values << endl;
cout << "The average is " << avg << endl;
return 0;
}
Starting with just these 3 lines of code:
double numValues = 0; //# of values in list
int values; //numbers in list
double avg = values / numValues;
at this point avg is UNINITIALIZED divided by ZERO, which is not good in multiple ways. I'd think the compiler would have a lot to say about this.
values actually has to be accumulated before its average can be calculated, and values is never accumulated into anything, you just read it in over and over.
...C++ is imperative, not declarative like Excel.
In addition to dirck's observation that you are computing the results before you have the data, there is much more wrong with it.
You are reading the same value over and over, not making a collection of values and not summing the values read.
while (inFile >> values);
has nothing to do with stopping at the sentinel, and the following block of code will test the last value read (only), which is the last value in the file.
This question already has answers here:
How to check if the input number integer not float?
(3 answers)
How to check if the input is a valid integer without any other chars?
(7 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I am new to c++ - and I am having trouble to validate user that the input must be a integer, and I just want the basic - simpler way, for me to understand. (Just basic way) to validate the input of the user How can I make it to work prior to my code below. Thank you for you're help and you're time. For example: if I get prompt to enter positive number and Input the letter x that means it will show "Invalid entry".. thank you!
Here is my code:
Updated
if (cin >> x && x < 0) {
} else {
cout << "Invalid entry, Try again." << endl;
cin.clear();
while (cin.get() != '\n');
}
#include <iostream>
#include <fstream> // for file stream.
using namespace std;
int main() {
// Variables
int x, reversedNumber, remainder;
// Creating String variables and setting them to empty string.
string even = "", odd = "";
// Creating a file.
ofstream out;
out.open("outDataFile.txt");
// creating a character variable
// for the user input if they want to use the program again.
char ch;
do {
// Even number.
even = "";
// Odd number.
odd = "";
// Reversed number
reversedNumber = 0;
// Prompt the user to enter a positive integer.
cout << "\nEnter a positive integer and press <Enter> ";
// Validate user input.
while (cin >> x || x < 1) {
// Clear out the cin results.
cin.clear();
// Display user that it is not a positive integer.
cout << "Invalid entry, Try again. ";
}
// Display Results to the screen
cout << "the original number is " << x << "\n";
// Display results in the text file.
out << "the original number is " << x << "\n";
// Display number reversed.
cout << "the number reversed ";
// Display number reversed in text file.
out << "the number reversed ";
//Reversing the integer.
while (x != 0) {
remainder = x % 10;
reversedNumber = reversedNumber * 10 + remainder;
// Display on screen
cout << remainder << " ";
// Display in text file.
out << remainder << " ";
x /= 10;
}
// Display the results on screen and in the text file.
cout << "\n";
out << "\n";
// Reading the reverse numbers result.
while (reversedNumber != 0) {
remainder = reversedNumber % 10;
// Checking if the number is even or odd.
if (remainder % 2 == 0) {
// even = even * 10 + remainder;
} else {
// odd = odd * 10 + remainder;
}
reversedNumber /= 10;
}
//Displaying the even numbers.
if (even != "") {
cout << "the even digits are " << even << "\n";
out << "the even digits are " << even << "\n";
}
// If it is not even then display..
else {
cout << "There are no even digits \n";
out << "There are no even digits \n";
}
//Display the odd results.
if (odd != "") {
cout << "the odd digits are " << odd << "\n";
out << "the odd digits are " << odd << "\n";
}
// If its not odd then display.
else {
cout << "There are no odd digits \n";
out << "There are no odd digits \n";
}
// just a divider to divide the results inside text file.
out << "----------------- \n";
// Prompt the user if they want to use the program again.
cout << "\nDo you like to continue/repeat? (Y/N):";
// get the input from user.
cin >> ch;
if ((ch == 'Y') || (ch == 'y')) {
} else {
cout << "\nGoodbye!" << endl;
}
} while (ch == 'y' || ch == 'Y');
// close the text file.
out.close();
return 0;
}
You could read a string from cin and check each character to make sure that when passed to isdigit() it returns true.
std::string x;
std::cin >> x;
for(char c : x){ //for each char c in string x
if(!isdigit(c)) //Invalid
}
I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;
could you please help me with solving simple problem? I am very fresh with C++ and learning from book "Programming: Principles and Practice Using C++ by Bjarne Stroustrup". I have never learnt C++ before so I am not familiar with many useful features. The drill says:
"6. Now change the body of the loop so that it reads just one double
each time around. Define two variables to keep track of which is the
smallest and which is the largest value you have seen so far. Each
time through the loop write out the value entered. If it’s the
smallest so far, write the smallest so far after the number. If it is
the largest so far, write the largest so far after the number"
I do not know how to do this correctly without using vector. Here is my code:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
And here are previous steps, these I have solved with code above:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
Could you give me some hint how to do step 6.? I had some ideas but none of them worked..
Here is new code:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
I do not know how to do this correctly without using vector.
You do not need vector for this. The description correctly says that two variables would be sufficient:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
Modify your loop to read into a, not into both a and b. Check the newly entered value against smallestSoFar and largestSoFar, do the printing, and re-assign smallest and largest as necessary. Note that the first time around you should see both printouts - for largest so far and for smallest so far.
Based on the knowledge that you are suppose to know at the current stage for the this assignment. The code should go something like this:
#include < iostream>
#include < cstdlib>
int main() {
double num_1 = 0;
double num_2 = 0;
double largest = 0;
double smallest = 0;
bool condition1 = true;
while (true) {
std::cin >> num_1;
if (num_1 > largest){
largest = num_1;
}
else if (num_1 < smallest) {
smallest = num_1;
}
std::cout << "The largest so far: " << largest << std::endl;
std::cin >> num_2;
if (condition1) {
smallest = largest;
condition1 = false;
}
if (num_2 < smallest) {
smallest = num_2;
}
else if (num_2 > largest) {
largest = num_2;
}
std::cout << "The smallest so far: " << smallest << std::endl;
}
system("pause");
return 0;
}
double large = 0;
double small = 0;
double input;
int counter = 0;
while (counter < 5) {
cin >> input;
cout <<"Large value: "<< large << '\t' <<"Small value: "<< small\
<< '\t' <<"Input value: "<< input << '\n';
if (input < small) {
cout << "The smallest value is " << input<<\
"\nthe largest value is "<< large<<'\n';
small = input;
}
else if (input > small&& input < large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << large<<'\n';
}
else if (input > small&& input > large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << input << '\n';
large = input;
}
counter += 1;
I need to create a program that takes integers from a text file, and outputs them, including the number, lowest number, largest number, average, total, N amount of numbers, etc. I can do this just fine with the code below, but I also need to process the text per line. My sample file has 7 numbers delimited with tabs per row, with a total of 8 rows, but I am to assume that I do not know how many numbers per row, rows per file, etc. there are.
Also, for what it's worth, even though I know how to use vectors and arrays, the particular class that I'm in has not gotten to them, so I'd rather not use them.
Thanks.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int num;
int count = 0;
int total = 0;
int average = 0;
string str = "";
int numLines = 0;
int lowNum = 1000000;
int highNum = -1000000;
ifstream fileIn;
fileIn.open("File2.txt");
if (!fileIn) {
cout << "nError opening file...Closing program.n";
fileIn.close();
}
else {
while (!fileIn.eof()) {
fileIn >> num;
cout << num << " ";
total += num;
count++;
if (num < lowNum) {
lowNum = num;
}
if (num > highNum) {
highNum = num;
}
}
average = total / count;
cout << "nnTotal is " << total << "." << endl;
cout << "Total amount of numbers is " << count << "." << endl;
cout << "Average is " << average << "." << endl;
cout << "Lowest number is " << lowNum << endl;
cout << "Highest number is " << highNum << endl;
fileIn.close();
return 0;
}
}
One way to deal with the individual lines is to skip leading whitespaces before reading each value and to set the stream into fail-state when a newline is reached. When the stream is good after skipping and reading a value, clearly, there was no newline. If there was a newline, deal with whatever needs to happen at the end of a line, reset the stream (if the failure wasn't due to reaching eof()) and carry on. For example, the code for a loop processing integers and keeping track of the current line could like this:
int line(1);
while (in) {
for (int value; in >> skip >> value; ) {
std::cout << "line=" << line << " value=" << value << '\n';
}
++line;
if (!in.eof()) {
in.clear();
}
}
This code uses the custom manipulator skip() which could be implemented like this:
std::istream& skip(std::istream& in) {
while (std::isspace(in.peek())) {
if (in.get() == '\n') {
in.setstate(std::ios_base::failbit);
}
}
return in;
}