User input ending loops on C++ - c++

I am trying to create something (I'm thinking probably a loop?) that will allow me to have the user enter several numbers and then enter something like "done" to get all the numbers added up.
for example if I have a float (call it x for now) they could enter "7 enter 5 enter 9 enter done enter" and it would add those numbers and make x that value. Where I am coming into problems is that I need the user to be able to be able to enter as many numbers as they want (between 1 and 70 as an example) without specifying how many numbers they want to enter, just entering something in when they are done.
Thank you all

You'll need to use an infinite loop (while (true) or for (;;)) to read the next input into a string.
Check if the string is done. If so, break the loop.
Then try to parse that string into a double (don't use float) with the function std::stod.
If the parsing fails, optionally print an error message like "Bad input, try again" and restart the loop. If the parsing succeeds, add the number to the counter and restart the loop.

Related

How do you write a program that tests if a user's inputs are integers and returns a message if they enter characters?

The homework is that you need to write a program that takes 4 integers between 0-100 inclusive from the user, computes their average, and displays the four integers as well as the average on the output screen, like in the following format:
Your grades were: 70 80 60 90
Your average grade is 75
You also have to make sure that the program produces a mathematically correct result, which it may not because of integer division. You also have to make it that the user cannot enter numbers outside the range 0-100, and the user cannot enter characters or strings.
So far, I have met the first two restrictions, however I am having trouble setting up the code such that the user cannot enter any characters. Can someone take a look at the following code and see what I'm doing wrong? Note that this is only the part of the code that pertains to my issue.
int main()
{
int grade1, grade2, grade3, grade4;
float grade_average;
char g1char;
cout << "Enter 4 integer grades (%): ";
cin >> grade1 >> grade2 >> grade3 >> grade4;
g1char = grade1;
if (isdigit(g1char) == 0) {
cout << "Incorrect input - characters not allowed; Please run the program again and enter proper values";
}
The function std::isdigit expects an int with the value of a character code. However, you are not passing it a character code. If you want to pass a character code, you must read the input as a string or as individual characters, not as a number. Otherwise, you will have no character codes to pass to std::isdigit.
However, unless the task description explicitly requires you to check that every single character is a digit, you don't have to call std::isdigit. This would also not be meaningful in some cases. For example, when the user enters negative numbers such as -34, the first character is not a digit. With this specific task, the user is not supposed to enter negative numbers, but the user may want to enter +34 for the number 34, which should also be valid (unless the task description explicitly states otherwise).
You have two options to solve this problem. You can either
rely on the stream extraction operator >> and check whether an error occurred using std::cin.fail, or
read one line of input as a string using std::getline, and use std::stoi to attempt to convert the string into to a number. The function std::stoi will tell you whether the input was valid or not, i.e. whether it was possible to convert the string to a number.
The first option may be easier to use, but the second option is generally recommended for line-based user input, as it will always read one line at a time.
However, both options do have one problem: They will accept input such as 6sdfh4q as valid input for the number 6. Therefore, if you want perfect input validation, you should also check the part of the input that was not converted to a number, to check whether it is acceptable. All whitespace characters are probably harmless, but all other characters are not, so I recommend that you use std::isspace for this purpose.

What is the proper way to use continue?

I am running into problems accomplishing another iteration after using continue. The goal is to get an integer input that is greater than or equal to 3. I dont want the script to error out on the user, instead I would like to ask for another input.
while True:
try:
sides = int(raw_input("Marty wants to draw you a shape. How many sides will the shape have?"))
except ValueError:
print "Marty needs an integer, try again."
continue
if sides < 2:
print "Marty needs a number greater than 2, try again."
continue
else:
break
Does the issue come when using continue twice? Any advice in the proper use of continue would be great. As it stands now, it asks the user for an input. If given anything other than an integer, it asks for another input. If given 2 it does nothing, not even print, let alone try again for an input.
The problem isn't with your use of continue, it's with your evaluation of the input. Rather than what you have, try:
if sides <= 2:
print 'Marty needs a number greater than 2, try again.'
continue
or:
if sides < 3:

Xcode C++ Console: Is there a limit on number of input characters?

When I paste or type a string that contains ~1000 characters into the console, ¿'s (upside down question marks) start appearing in the input. Once they start appearing, I can't delete the characters I've entered, and pressing enter yields even more ¿'s. The program only continues after hitting delete once and pressing enter again.
When I cout << the string obtained from the input , an amount of characters about equal to the number of ¿'s that appeared in the input are missing from the string. There were no missing characters in the input, just the strange extra ¿'s.
It's not an issue with unknown characters, as it happens even with simple letters and digits. This doesn't happen when the input is entered in pieces. Is there some sort of limit on how many characters can be entered into the console at once, or is this a different error? And can it be fixed? Thanks!

Prompting User For Instructions

I am trying to write an infix calculator and I want to start the program off asking the user if he/she needs help or not. I have written the code that will offer instructions if the user inputs 'y' or 'n', however, in both cases, the program ends without allowing the user to enter an infix expression and running the rest of the program. It seems as though the program is breaking in main right after cout << "Expression?"; It does not give the option for the user to input anything after that.
When you use cin >> help, you're only reading one character, the y or n. The newline after that is left in the input buffer.
Then when the main function uses getline, it reads up to the next newline, which is the one that was left in the buffer by provideHelpIfNecessary. So it just reads a zero-length line, and that causes the while loop to break.
Use getline in provideHelpIfNecessary instad of reading just one character.

Restrict users to enter numbers valid only till 2 decimal places C/C++

I am making an currency change program where I would be providing exact change to the input amount, for example a value of 23 would be one 20 dollars and 3 one dollar bills
I want to restrict the user to input the value only till 2 decimal places. For example: the valid inputs are
20, 20.4, 23.44 but an invalid input would be 20.523 or 20.000.
How can I do this is C/C++.
I read about one function that is setprecision but that is not what I want, setprecision allows to display the value till that decimal point, it still doesn't stop the user from entering any value.
Is there any way to do this?
Read the amount from the user as a string, either character by character or the entire line, and then check its format, and then convert it.
It's generally easier to let the user type whatever they want followed by the program rejecting the input if it isn't valid rather than restricting what they can type on a keystroke basis.
For keystroke analysis you would need a state machine with 4 states, which we can call Number, Numberdot, Numberdotone, and Numberdottwo. Your code would have to make the proper transitions for all keystrokes, including the arrow keys to move the cursor to some arbitrary place and the Backspace key. That's a lot of work.
With input validation, all you have to do is check the input using a regular expression, e.g. ^(([0-9]+) | ([0-9]+.[0-9]) | ([0-9]+.[0-9][0-9])$. This assumes that "20." is not valid. Then if it's invalid you tell the user and make them do it again.
I do not believe that there is any way to set the library to do this for you. Because of that you're going to have to do the work yourself.
There are may ways you can do this, but the only true way to handle restricting the input is to control reading it in yourself.
In this case you would loop on keyboard input, for ever keystroke you would have to decided if it can be accepted in the context of the past input, then display it. That is, if there is a decimal point you would only accept to more numbers. This also allows you to limit input to numbers and decimal places as well, not to mention input length.
The down side is you will have to handle all the editing commands. Even bare bones you would need to support delete and enter.
This is rather a task for the GUI you are using, than for core C/C++. Depending on your GUI/Web Toolkit you can give more or less detailed rules how data can or can not be entered.
If you are writing a normal GUI application you can control and modify the entered keys (in C or C++).
In a WEB application you can do similar things using javascript.
The best solution would be when all illegal input is impossible.