Here is the objective: "Write a c++ program which prompts the user to enter some numbers and finds the minimum, maximum, and count
(number) of the entered numbers separately for the positive and negative numbers. It then prints out this information
in the correct format. Entering 0 should terminate the input sequence and cause the results to be displayed.
My problem is, when I run the code through www.cpp.sh, it seems to be storing the 0 that I use to end the sequence to a maximum or a minimum variable (posmax and negmax or posmin and negmin). My while loop's condition is number_entered !=0, so 0 shouldn't even be going into the loop...
if the first 3 in the sequence are negative and the last 3 are positive; if the first 3 in the sequence are positive and the last 3 are negative
Stranger still, the 0 being stored as a minimum or negative only seems to happen to the last sequence of variables entered.
Relevant code:
int main()
{
double number_entered, posmax, posmin, negmax, negmin;
int positive_count, negative_count;
positive_count = 0;
negative_count = 0;
posmax = 0;
posmin = 0;
negmax = 0;
negmin = 0;
//before it goes into a loop it will do the following:
cout << "Entering 0 will terminate the sequence of values.\n" << endl;
cout << "Enter a number: ";
cin >> number_entered; //stores input to number_entered
if (number_entered > 0) //if positive
{
posmax = number_entered; //needs to be initialized before use in loop
posmin = number_entered; //needs to be initialized before use in loop
}
else if (number_entered < 0) //if negative
{
negmax = number_entered; //needs to be initialized before use in loop
negmin = number_entered; //needs to be intiialized before use in loop
}
while (number_entered !=0) //will keep looping as long as the while condition is true
{
if (number_entered > 0) //branch if number_entered is positive
{
if ( number_entered > posmax) //sub-branch to compare to get max
{
posmax = number_entered; //if number is larger than the current max, it gets stored as the new max
}
else if ((number_entered < posmin)||(posmin == 0)) //sub-branch to compare to get min; since posmin is initialized to 0 it needs to be updated
{
posmin = number_entered; //if number is less than min than it gets stored as the new min
}
positive_count++; //under main if branch for if the number is positive, add to positive_count
}
else if (number_entered < 0) //branch for if number_entered is negative
{
if ( number_entered > negmax) //sub-branch if number_entered is more than the max
{
negmax = number_entered; //it then gets stored as the new negmax
}
else if ((number_entered < negmin)||(negmin == 0)) //sub-branch if number_entered is less than min; since negmin is initialized to 0 it needs to be updated
{
negmin = number_entered; //it then gets stored as the new negmin
}
negative_count++;
}
cout << "Enter a number: "; //prompts for input again after it is done counting, and comparing to store a max and min
cin >> number_entered;
} //end of while loop
if (number_entered == 0)
{
cout << endl;
if ((negative_count > 0) && (positive_count > 0)) //for situations where it received both positive and negative values
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
}
else if (negative_count > 0 && positive_count == 0) //for sitautions where only negative input was received
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "No positive numbers were entered" << endl;
}
else if (positive_count > 0 && negative_count == 0) //for situations where only positive input was received
{
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
cout << "No negative numbers were entered" << endl;
}
else if (negative_count == 0 && positive_count == 0) //for if only 0 was received
{
cout << "No positive numbers were entered.\n"
<< endl
<< "No negative numbers were entered.\n"
<< endl;
} //end of nested branching if-else if statement
} //end of if statement
return 0;
}
I figured it out finally, but maybe I posted the answer badly and that was why I didn't get the answer I needed.
in order to get a max that wasn't 0 for the negative values, I simply needed to move my || (negmax == 0) condition to the correct if statement (it was on the minimum branch).
There were no other issues with the program.
Because your initial values are zeros. There is no way that you will enter number lower (for positives) and higher (for negatives) than zero.
Related
I am trying to minimize hardcoding numbers into my program and allowing for users to define max and min parameters along with making sure that the input is valid.
#include <iostream>
int main(){
int max, A=0;
do
{
std::cout << "What is the max?\n";
std::cin >> max;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore();
std::cout << "not an integer, try again\n";
continue;
}
if(max < -1000){
std::cout << "That doesnt make much sense, please enter the max again.\n";
}
} while (max <A); \\HERE IS WHERE THE PROBLEM IS.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
If A is 0 or less, the program doesn't ask for user input again. instead the program just exits the loop.
If A is 1 or more, then then the program loops until a valid input is provided.
I would like the max number to be any int number, including negatives. This is working for positive numbers, but not for maximums that are 0 or less.
do
{
//ask for input
//input taken
} while (A>=1);
This will the code you have to use for the scenario described at the last line. One more point you just forget to assign any value to A according to your logic.
Thanks!
If A is 1 or more, then then the program loops until a valid input is provided. - You are saying exactly what the while loop needs to do. Just implement it.
} while (A >= 1); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
To answer your follow up question:
} while (A >= 1 && max <= 0); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
I would suggest writing a custom function that takes an acceptable range of min/max values as input parameters, eg:
int promptForInt(const string &prompt, int minAllowed, int maxAllowed)
{
int value;
std::cout << prompt << "\n";
do
{
if (!(std::cin >> value)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "not an integer, try again\n";
continue;
}
if ((value >= minAllowed) && (value <= maxAllowed)){
break;
}
std::cout << "not an allowed integer, enter a value between " << minAllowed << " and " << maxAllowed << ".\n";
}
while (true);
return value;
}
int main(){
int max = promptForInt("What is the max?", -1000, 1000);
std::cout << "The max number of steps are " << max << std::endl;
return 0;
}
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;
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 have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer
void offer_help();
bool play_one_game();
int main() {
offer_help();
play_one_game();
}
void offer_help() {
int help_response;
cout << "Need help? (0/1) ";
cin >> help_response;
if (help_response == 1)
cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n Each guess that you enter will be a line containing 4 integers,\n separated by spaces, such as:\n\t 2 4 7 1\n FOr each guess, I will echo back a lost consisting of\n 0's and 1's, with a 1 in a given position meaning that\n you guessed the number, and a zero meaning that you didn't.\n For example, if the actual solution was 2 3 6 1, I'll respond\n\t 1 0 0 1\n See how many guesses it takes you to get the solution!\n\n If you want to give up, type a negative number for one of\n your guesses, and we'll tell you what the pattern was.\n\n";
}
bool play_one_game() {
srand(time(0)); //needed to start randint
vector<int> solution; //vector of 4 randomly generated
//solutions
vector<int> guess; //vector containing user guesses.
vector<int> result;
int guess_input;
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
int trial_number = 0; //int that shows what guess the user is on
while (play_one_game() == true) {
//ask user for inputs.
cout << "Guess #" << ++trial_number << "? ";
for (int i = 0; i < guess.size(); ++i){
cin >> guess_input;
guess.push_back(guess_input);
}
//outputs error if user inputs a letter.
if (!cin) {
cerr << "Bad input data! Feed me numbers!\n";
return 43;
}
if (cin < 0){
cout << "Too bad! Solution was " << endl;
for(int i = 0; i < result.size(); i++)
cout << (result[i]);
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
for (int i = 0; i < result.size(); i++) {
if (guess[i]==solution[i])
cout << 1 << " ";
else if (guess[i]!=solution[i])
cout << 0 << " ";
}
cout << endl;
// playagain();
cout << endl << "Play again (0/1)? ";
int replay;
cin >> replay;
if (replay == 0) {
play_one_game() == false;
return 5;
}
else if (replay == 1)
play_one_game() == true;
else {
cerr << "wat?\n";
return 10;
}
}
}
This is designed to allow a player to guess a pattern of random numbers.
No idea why I am getting a segmentation fault. The program is supposed to call the offer_help function, then the play_one_game function within main function. Then it should ask the player whether he wants to play again. If no, then bool play_one_game should be set to false and it should exit.
This is related to the play_one_game bool function.
You're getting a segmentation fault, because you end up in an endless recursion in the following line:
while (play_one_game() == true) {
play_one_game will call play_one_game in this line, and this will call play_one_game in the same line again. This will result in a stack overflow at last.
Better use some bool keepPlaying; and while(keepPlaying) instead.
EDIT: Well, this is a little bit more than a simple answer, but I like games, so... have a look at the following code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
bool play_one_game();
void offer_help() {
int help_response;
std::cout << "Need help? (0/1) ";
std::cin >> help_response;
if (help_response == 1)
std::cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n"
"Each guess that you enter will be a line containing 4 integers,\n"
"separated by spaces, such as:\n"
"\t 2 4 7 1\n"
"For each guess, I will echo back a lost consisting of\n"
"0's and 1's, with a 1 in a given position meaning that\n"
"you guessed the number, and a zero meaning that you didn't.\n"
"For example, if the actual solution was 2 3 6 1, I'll respond\n"
"\t 1 0 0 1\n"
"See how many guesses it takes you to get the solution!\n\n"
"If you want to give up, type a negative number for one of\n"
"your guesses, and we'll tell you what the pattern was.\n\n";
}
int main() {
offer_help();
srand(time(0)); // Initialize random numbers with current time as seed
while(play_one_game()); // if play_one_game returns true, play again
}
bool play_one_game() {
std::vector<int> solution(4); // Four solutions for our guessing game
std::vector<int> guess; // User guesses
for(unsigned i = 0; i < solution.size(); ++i)
solution[i] = rand() % 10;
int trial_number = 0; //int that shows what guess the user is on
bool keepPlaying = true;
while(keepPlaying){
std::cout << "Guess #" << ++trial_number << "? ";
guess.clear(); // Clear old guesses
for(unsigned i = 0; i < solution.size(); ++i){
int guess_input;
//outputs error if user inputs a letter.
if (!(std::cin >> guess_input)) {
std::cerr << "Bad input data! Feed me numbers!\n";
std::cerr << "Try again!" << std::endl;
std::cin.clear(); // Clear flags
continue;
}
if (guess_input < 0){
std::cout << "Too bad! Solution was " << std::endl;
for(unsigned i = 0; i < solution.size(); i++)
std::cout << (solution[i]);
keepPlaying = false;
break;
}else
guess.push_back(guess_input);
}
if(!keepPlaying)
break;
if(solution.size() != guess.size()){
std::cerr << "Wrong number of guesses, try again!" << std::endl;
continue;
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
bool correct = true;
for (unsigned i = 0; i < solution.size(); i++) {
if (guess[i] == solution[i])
std::cout << 1 << " ";
else{
correct = false;
std::cout << 0 << " ";
}
}
if(correct){
std::cout << "Congratulations - you won!" << std::endl;
break;
}
std::cout << std::endl;
}
int replay = -1;
do{
// Ask user for input until input is 0 or 1
std::cout << std::endl << "Play again (0/1)? ";
std::cin >> replay;
}
while(replay != 0 && replay != 1);
return static_cast<bool>(replay); // return user replay answer (false/true)
}
Try to keep your code as simple as possible. Welcome to SO. And don't expect future answers to be that excessive.
You're never inserting anything into your solution vector. You just declare the vector, and then say:
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
...which won't do anything since at this point solution.size() == 0. Later, when you iterate over your result vector, you end up accessing invalid elements in your empty solution vector. You also can't assume that the result vector and solution vector are the same size.