C++ function to check if an input is an integer? - c++

I'm currently writing a C++ program for school that involves taking an input as an amount of change, then telling the user how many quarters, dimes, nickels, and pennies they require to make said change.
However, if the user inputs any sort of character or string the program goes into an infinite loop printing two or three of my messages indefinitely.
Is there a function or some other method I can use to prevent this from happening?
Edit: Here's some of my code that I think represents the issue
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
#include <sstream>
using namespace std;
int main ()
{
cout << "\nMake Change v0.6.4\n";
cout << "Type 0 at any time to exit the program.\n";
char confirmExit;
int amount;
while (tolower(confirmExit) != 'y')
// allows the user to continue using the program with having to type a.out everytime
// but quit the application at any time with two keystrokes and
// confirmation so as to not accidentally exit the program
{
cout << "\nEnter the amount of change as an integer: ";
// input total cents to be worked with
cin >> amount;
if ((amount)!int)
{
cout << "\nMake sure to type an integer!\n";
}
else if (amount == 0)
{
cout << "Are you sure you want to exit the program(y/n)? ";
cin >> confirmExit;
// confirmation to prevent accidentally exiting out
}
cout << "\n";
return (0);
}

In C++ everything is bits and implicit conversion can takes place to convert string or other forms of data to int value. You can use limits header file in standard library and set the bound for max and min value of input.If you can't get it then comment below. I will post code.
This link might be useful-
Visit http://lolengine.net/blog/2012/02/08/selectively-restrict-implicit-conversions

see the functions defined below:
atoi
strtol

Related

std::cin is not accepting input

I am trying to get the first program working from "Accelerated C++".
I was having trouble getting the program to stay open without shutting down, so I decided to put a int i = 0; and cin >> i; after main() returns. Unfortuantely, it doesn't seem to take any input, no matter where I put that cin statement.
If it helps, it is using an istream reference to accept cin input. I can't figure out how to enter code on this site.
For most of my adult life, I used system("PAUSE") without any problems to keep the program window open. It's not good for real-time systems, of course, but it's simple and powerful because you're actually running a console command and it can be used to make console scripts.
#include <iostream>
#include <cstdlib>
using namespace std;
inline void Pause () { cout << "\n"; system ("PAUSE); }
int main () { Pause (); }
This solution is not 100% portable, but it will work on PCs. A more portable solution is:
#include <conio.h>
#include <cstdio>
void Pause() {
cout << "\nPress any key to continue...";
while (_getch() < 0)
;
}
cin is good for doing simple things, but what I do is wrap the std library in C functions and use those because it can dramatically improve compile times to hide the std library headers in the implementation files.
The prefered method in C++ is std::getline() using std::string, though many teachers won't let you use that.
With cin, you also have to clear input errors and use ignore() to throw away a specific number of chars.
#include <string>
string foo;
cout << "Why do they always use foo? ";
getline (cin, foo);
cout << "You just entered" << foo;
int bar;
cout << "\nThe answer is because programmers like to go to the bar."
"\nHow many times have you seen foo bar in an example? ";
while (!(cin >> bar)) {
cout << "\nPlease enter a valid number: ";
cin.clear ();
cin.ignore (10000, '\n');
}
My many years of experience have taught me to put the \n char at the beginning of output lines as opposed to the end of them.

Why is this code exiting at this point?

I'm new to C++. I stumbled upon one tutorial problem, and I thought I'd use the few things I have learnt to solve it. I have written the code to an extent but the code exits at a point, and I really can't figure out why. I do not want to go into details about the tutorial question because I actually wish to continue with it based on how I understood it from the start, and I know prospective answerers might want to change that. The code is explanatory, I have just written few lines.
Here comes the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double average_each_student() {
cout << "\n>Enter your scores seperated by spaces and terminated with a period\n"
<< ">Note: scores after total number of six will be truncated.\n"
<< endl;
double sum = 0, average = 0;
int user_input, counter = 0;
const double no_of_exams = 6;
while(cin >> user_input) {
++counter;
if(counter < 5) sum += 0.15 * user_input;
else if(counter > 4 && counter < 7) sum += 0.20 * user_input;
}
return sum / no_of_exams;
}
int reg_number() {
cout << "Enter your registration number: " << endl;
int reg_numb;
cin >> reg_numb;
return reg_numb;
}
int main() {
vector<int> reg_num_list;
vector<double> student_average;
reg_num_list.push_back(reg_number());
student_average.push_back(average_each_student());
string answer;
cout << "\n\nIs that all??" << endl;
//everything ends at this point.
//process returns 0
cin >> answer;
cout << answer;
}
The code exits at cout << "\n\nIs that all??" << endl;. The rest part after that is not what I intend doing, but I'm just using that part to understand what's happening around there.
PS: I know there are other ways to improve the whole thing, but I'm writing the code based on my present knowledge and I wish to maintain the idea I'm currently implementing. I would appreciate if that doesn't change for now. I only need to know what I'm not doing right that is making the code end at that point.
The loop inside average_each_student() runs until further input for data fails and std::cin gets into failure state (i.e., it gets std::ios_base::failbit set).
As a result, input in main() immediately fails and the output of what was input just prints the unchanged string. That is, your perception of the program existing prior to the input is actually wrong: it just doesn't wait for input on a stream in fail state. Since your output doesn't add anything recognizable the output appears to do nothing although it actually prints an empty string. You can easily verify this claim by adding something, e.g.
std::cout << "read '" << answer << "'\n";
Whether it is possible to recover from the fail state on the input stream depends on how it failed. If you enter number until you indicate stream termination (using Ctrl-D or Ctrl-Z on the terminal depending on what kind of system you are using), there isn't any way to recover. If you terminate the input entering a non-number, you can use
std::cin.clear();
To clear the stream's failure stated. You might want to ignore entered characters using
std::cin.ignore(); // ignore the next character
or
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ignore everything up to the end of the line
use cin.clear(); before cin >> answer; That will fix the problem. But you are not controlling the input. it just runs out to cin..

how to set time for reading an input using getline in c++?

i am trying to develop a program that it waits for particular period of time for input and comes out after some time in c++ ,like we do in atm machine .
can anyone try to help me.
#include <iostream>
#include <ctime>
#include<string>
using namespace std;
int main(){
string name;
cout << "Enter your name: ";
int endTime= 5;
int i=0;
// cout<<endTime<<endl;
while(i < endTime)
{
getline(cin, name);
i++;
endTime--;
if( i > endTime && (name.empty()))
break;
}
cout << "NO NAME ENTERED!!" << endl;
Part of your problem is that getline() is a blocking call, and won't return until someone inputs something.
What you could do is to research threading - have two different threads, one of which has the sole responsibility to watch time, and if the time has passed, then you send a signal to kill the other thread.
You are limited a lot by the input method that you showed here.

functions not returning values that a user enters

I AM working on this program for an assignment, so I don't want the answer...just a push in the right direction.
I have written a program in which a user will input a 3-digit ID (required) and an amout of KWh used for the month. After that criteria has been entered, it will print out a short summary + the charges for that month per user. And this is enclosed in a loop to ask if there are any more IDs to be entered.
Below is my opening code and loop structure:
#include <iostream>
#include <string>
#include <iomanip>
#include <windows.h>
using namespace std;
//function prototypes
string get_user_ID();
int get_cust_kwh();
string display_cust_data();
int main()
{
string userID;
int userKWH;
char answer;
while ((answer !='N')&&(answer !='n')){
userID = get_user_ID();
userKWH =get_cust_kwh();
display_cust_data();
cout << "\n\nWould you like to add another utility ID? : (Y or N)";
cin >> answer;
}
}
system("pause")
return 0;
I can get the loop to function correctly, but my functions don't seem to be returning the values that the user enters. As I am new to functions, I am sure it's some silly mistake, but one that has been driving me crazy. Here are the functions:
**********function definitions**********
string get_user_ID(){
string usrID;
cout << "\n\nPlease enter in your 3-digit utility ID: ";
cin >> usrID;
return usrID;
}
int get_cust_kwh(){
int usrKWHs;
cout << "Please enter the total KWH used for the month: ";
cin >> usrKWHs;
return usrKWHs;
}
string display_cust_data(){
string usrID;
int usrKWHs;
double userCharge;
cout << "\n\nUSER ID KWHours Charge($)\n";
cout << fixed << setprecision(2);
cout << usrID << " " << usrKWHs << " " << userCharge << endl;
}
I'm thinking something to do with the way the variables in the functions are used.
Thanks for any pushes you can give!
The problem is display_cust_data() doesn't know about variables in main function scope. What you are printing is just the local variables which has garbage values.
string display_cust_data(){
string usrID; // This is a different variable and is not equivalent to the
// variable in main.
Also why the function's return type is string ?
Look at your display_cust_data. How does it get any information about what to display?
You need to find a way to pass the user input variables to your display function. The variables you have in the display_cust_data() function are newly created there and are not the same as the variables you have in your while loop in your main() function. All of the variables you display in that function are uninitialised and so you have no idea what their values will actually be. Consider adding arguments to the function so that when you call it you can pass the user input variables to it so that you can display the values you want to display.

C++ cin positive integers only

This is my first time on Stackoverflow.
I was making a program to find out MPG for a car. I was wondering how can I make the cin statement only accept positive integers only? and also, if you do enter a invalid input, can you reset it? I am not sure if that makes sense. I didn't have to do this for class. I was just curious on how to do it. Here is the code.
#include <iostream>
using namespace std;
int main()
{
double tank, miles, mpg;
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
mpg = (miles)/(tank);
cout << "Your vehicle recieves " << mpg << " miles per gallon\n" << endl;
system ("pause");
return 0;
}
iostreams are not a toolkit for building a complex UI. Unless you want to write your own rather complex stream to wrap the usual stream, there is no way you are going to get it to either (a) only accept positive integers or (b) interact politely with a user who types in something else.
You should just read lines from cin, and print your own error prompts and such after you look at what you get.
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
do
{
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
} while (tank <= 0 && ((int)tank != tank));
do
{
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
} while (miles <= 0 && ((int)miles != miles));
If you do this after running the statements it will rerun them if the answer is 0 or lower or is not an integer. If you make the variables ints instead of doubles then you can remove the "&& ((int)miles == miles)" part of the while statement.
Still, there are a couple of standard ways to do it in a command line environment.
You could trap the cin statement in a loop that doesn't release until a valid input has been entered. This is the "standard" way to validate CLI input, not just signed numbers.
do
{
cout << "\nPlease enter...";
cin >> tank;
}
while (tank < 0)
The condition in the while statement is the place to validate the data. You can also make an if statement to explain why the input is invalid.
The other way is to simply force the value to be positive, by simply going tank = fabs(tank);, which takes the absolute value (i.e. positive) of the tank variable.
So this is my code for an infinite loop
1: So main will call the "Get_number()" function
2: Get number will accept an int from the user
3(A): If int is greater than 0, go into loop
3(B): Else, display to user "Invalid Input" and then call the function
"Get_number()" again creating an infinite loop until the user
enters a value greater than 0
#include <iostream> // Access the input output stream library
#include <fstream> // Access to the fstream library (used to read and write to files)
#include <chrono> // Needed to access "std::chrono_literals"
#include <thread> // Needed to access "namespace std::this_thread"
using std::fstream; // this will allow us to use the fstream (we'll be able to read and write to files)
using std::ios; // needed for iostream (used to be able to tell fstream to read and/or write to a file and that it's reading/writing a binary file)
using std::cout; // need this statment to access cout (to display info to user)
using std::cin; // need this statment to access cin (to gather info from user)
using std::endl; // need this statment to access endl (will end the line)
using namespace std::this_thread; // This will allow me to use "Sleep_For" or "Sleep_Until"
using namespace std::chrono_literals; // This will allow the use of measurements of time such as ns, us, s, h, etc.
//Prototypes***************************************************************************************************
void shellSort(int read[], int readLength); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Get_number();
void Write_to_file(int user_input_of_how_many_random_numbers_to_generate); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Read_from_file(int user_input_of_how_many_random_numbers_to_generate);//Making Prototype (Declaring our function) so that compiler knows not to worry about it
//*************************************************************************************************************
void main()
{
Get_number();
system("pause>>void"); // will let the console pause untill user presses any button to continue
}
/**************************************************************************************************************
* Purpose: This function will gather a positive integer from the user and use it to generate that many
* random numbers!
*
* Precondition: None
*
*
* Postcondition:
* Would've gathered the number of random numbers the user wanted to generate and then gone into the
* Write_to_file and Read_from_file function
*
**************************************************************************************************************/
void Get_number()
{
int user_input_of_how_many_random_numbers_to_generate = 0; //make variable that will accept the int value the user wants to generate random numbers
cout << "Please Enter A Number Greater Than Zero:" << endl; // displays to user to enter a number greater than zero
cin >> user_input_of_how_many_random_numbers_to_generate; // will accept the value the user inputted and place it in the "user_input_of_how_many_random_numbers_to_generate" variable
system("cls"); // Will clear the screen
if (user_input_of_how_many_random_numbers_to_generate > 0) // if user input is greater than zero, enter this
{
Write_to_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Write_to_file" function
Read_from_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Read_from_file" function
}
else // else enter this
{
cout << "invalid input!" << endl; // display to user "invalid input"
sleep_for(2s); // system will pause for 2 seconds allowing the user to read the message of "invalid input"
system("cls"); // console will be cleared
Get_number(); // Get_number function will be entered creating an infinate loop untill the user's input is valid!
}
}
Instead of
cin >> miles;
Try
while ( (cin >> miles) < 0 )
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
That will repeat the question until the input is positive. You can do that for the rest of the questions too.
Note that input streams are not intended for input filtering. You have to provide your own logic for that.