简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM