I'm trying to make the program exit properly without it. I have '|' as my exit, if its the first thing I do when first running, it closes fine. But after entering values and printing them, afterwards entering '|' to exit.
It prints out:
"The smaller value is 0
The larger is previous second value" // want to remove this from showing
int main()
{
double first = 0, second = 0;
while(cin.good()){
char exit;
cout << "Enter '|' to exit.\n";
cout << "Enter two numbers:";
cin >> first >> second;
exit = cin.peek();
if(exit=='|'){
break;}
else{
if(first<second){
cout << "\nThe smaller value is " << first << "\nThe larger value is " << second << endl;
}
else if(first>second){
cout << "\nThe smaller value is " << second << "\nThe larger value is " << first << endl;
}
}
}
}
In your code, you've assumed that the input from your users will be limited to something usable as a double. This isn't necessarily the case. The issue that you're running into isn't related to the statement exit = cin.peak(); but to cin >> first >> second; You can test this by entering any non-numerical input into your program and watching it fail by assigning a 0 to the first and leaving second as is.
In short, because the conversion of the input into a double fails, you get an indeterminate value for first and then your program moves on.
You can use the following code as an example. In this, I first populate my variables as strings, then attempt a conversion after the fact.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string str_first, str_second;
double first = 0, second = 0;
while(cin.good()){
cout << "Enter '|' to exit.\n";
cout << "Enter two numbers:";
cin >> str_first >> str_second;
if( (str_first.compare("|") == 0) || (str_second.compare("|") == 0) ){
cout << "\nThanks for playing\n" << endl;
break;}
else{
first = strtod (str_first.c_str(), NULL);
second = strtod (str_second.c_str(), NULL);
if(first<second){
cout << "\nFirst is small: The smaller value is " << first << "\nThe larger value is " << second << endl;
}
else if(first>second){
cout << "\nSecond is small: The smaller value is " << second << "\nThe larger value is " << first << endl;
}
}
}
}
Related
I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}
just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
first time poster here.
Please keep in mind I'm still very new to c++ and coding in general.
I'm trying to rewrite a program that asks the user how many numbers they want to compare, then they enter the values of each number. I have achieved this via for and if statements, but i am now asked to do this with user defined functions instead. The problem I have so far is that the first number I enter is the one saved, but it does prompt for additional numbers and the for loop inside of the function works properly. Some suggestions to what I'm not doing correctly would be greatly appreciated. I have all the variables declared that are needed, so i only put the prototype in to save on space.
int main()
{
int DisplayGreatest(int,int);
do {
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cin >> currentAinput;
DisplayGreatest (Aselection,currentAinput);
cout << "The largest number is "<< currentAinput << endl;
}
}
}
The function:
int DisplayGreatest(int Aselection, int currentAinput)
{
int i;
int keepAinput=0;
for(i=1;i<Aselection;i++)
{
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput=currentAinput;
}
}
return currentAinput;
}
You have several errors in your code:
First you are not using the returned value from the function DisplayGreatest
You are never comparing the first value you enter with the others (you do two cin in a row without before the first comparison)
Declaring the function DisplayGreatest in the wrong scope (should be in the global scope, or place the whole function before main)
You have no end condition to your do-loop in main. (missing while statement, maybe you have that in your own version)
You returned the last value entered in the DisplayGreatest function, not the largest one.
Here is a functional version:
#include <iostream>
using namespace std;
int DisplayGreatest(int Aselection)
{
int keepAinput = 0;
int currentAinput;
do {
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput = currentAinput;
}
} while(--Aselection > 0);
return keepAinput;
}
int main()
{
char Selection;
do {
int Aselection;
int currentAinput;
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cout << "The largest number is "<< DisplayGreatest (Aselection) << endl;
}
} while(Selection != 'C' && Selection != 'c');
}
int DisplayGreatest(int,int) should probably be declared in the global namespace, ie:
int DisplayGreatest(int, int);
int main()
{
}
int DisplayGreatest (int Aselection, int currentAinput)
{
}
Also, you can take in input in a loop but it is somewhat more natural take in a whole vector worth of ints and then find the highest/lowest using the same idea (loop through each one and save the current highest/lowest).
EDIT: Oh, I see what your issue is now. You need to return keepAinput at the end of your function and assign it to currentAinput or another variable and print whichever you assign it to. Or just print the result directly, IE:
cout << "Highest number is " << DisplayGreatest(Aselection, currentAinput) << endl;
I recently created a program that will create a math problem based on the user input. By entering either 1-4 the program can generate a problem or the user can quit by entering 5. The only problem I am having is that when I enter a character the program goes into an infinite loop. What function could I use to check if the input is not a number so I can display an error message?
//CIS180 Assignment #4
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//Declare variables.
int num1, num2, menuNum;
int addInput, subInput, multInput, divInput;
int addAnswer, subAnswer, multAnswer, divAnswer;
int addSolution, subSolution, multSolution, divSolution;
srand(time(0));
//Display menu.
cout << "Menu" << endl;
cout << "1. Addition problem" << endl;
cout << "2. Subtraction problem" << endl;
cout << "3. Multiplication problem" << endl;
cout << "4. Division problem" << endl;
cout << "5. Quit this program" << endl << endl;
cout << "Enter your choice (1-5): " << endl;
cin >> menuNum;
//Loop that will provide math problems when user inputs number.
while(menuNum != 5)
{
//Check if the input is valid.
while((menuNum < 1) || (menuNum >5))
{
cout << "The valid choices are 1, 2, 3 , 4, and 5. Please choose: " << endl;
cin >> menuNum;
}
//Generate two random numbers for addition and display output.
if(menuNum == 1)
{
num1 = rand()%500 + 1;
num2 = rand()%500 + 1;
addSolution = num1 + num2;
cout << setw(5) << right << num1 << endl;
cout << setw(2) << left << "+" << setw(3) << right << num2 << endl;
cout << setw(5) << fixed << "-----" << endl;
cin >> addAnswer;
//Check if the addition answer input is correct.
if(addAnswer != addSolution)
cout << "Sorry, the correct answer is " << addSolution << "." << endl;
else if(addAnswer == addSolution)
cout << "Congratulations! That's right." << endl << endl;
}
.
.
.
First off, you should detect whether your input attempt was successful: always check after reading that the read attempt was successful. Next, when you identify that you couldn't read a value you'll need to reset the stream to a good state using clear() and you'll need to get rid of any bad characters, e.g., using ignore(). Given that the characters were typically entered, i.e., the user had to hit return before the characters were used it is generally reaonable to get of the entire line. For example:
for (choice = -1; !(1 <= choice && choice <= 5); ) {
if (!(std::cin >> choice)) {
std::cout << "invalid character was added (ignoring the line)\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
The use of std::numeric_limits<std::streamsize>::max() is the way to obtain the magic number which makes ignore() as many characters as necessary until a character with the value of its second argument is found.
Read a single character
If this character is a digit, use it.
If this character wasn't a digit, goto 1.
Actually, forget about step 2. Just check whether it was one of the digit characters you actually want ('1', '2', '3', '4', '5'):
char choice;
while(cin.get(choice)){
if(choice == '5')
break;
switch(choice){
default: printWrongCharacterMessage(); break;
case '1': do1Stuff(); break;
case '2': do2Stuff(); break;
case '3': do3Stuff(); break;
case '4': do4Stuff(); break;
}
}
You can use isdigit from ctype.h
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;