Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking cin input stream produces an integer

Tags:

c++

cin

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.

How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.

Thanks

 #include <iostream>
using namespace std;

int main ()
{

    int firstvariable;
    int secondvariable;
    float float1;
    float float2;

    cout << "Please enter two integers and then press Enter:" << endl;
    cin >> firstvariable;
    cin >> secondvariable;

    cout << "Time for some simple mathematical operations:\n" << endl;

    cout << "The sum:\n " << firstvariable << "+" << secondvariable 
        <<"="<< firstvariable + secondvariable << "\n " << endl;

}
like image 406
user2766546 Avatar asked Sep 10 '13 21:09

user2766546


People also ask

How do you check that input is an integer?

Use the isnumeric() Method to Check if the Input Is an Integer or Not. The isnumeric() method of the string returns True if the string only contains numbers. However, it is worth noting that it fails with negative values. This is because it automatically returns False when it encounters the - sign in negative integers.

How do you check if an input is an integer in C++?

Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.


4 Answers

You can check like this:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}

Furthermore, you can continue to get input until you get an int via:

#include <iostream>



int main() {

    int x;
    std::cin >> x;
    while(std::cin.fail()) {
        std::cout << "Error" << std::endl;
        std::cin.clear();
        std::cin.ignore(256,'\n');
        std::cin >> x;
    }
    std::cout << x << std::endl;

    return 0;
}

EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}
like image 119
Chemistpp Avatar answered Sep 29 '22 12:09

Chemistpp


Heh, this is an old question that could use a better answer.

User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”

Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:

template <typename T>
std::optional <T> string_to( const std::string& s )
{
  std::istringstream ss( s );
  T result;
  ss >> result >> std::ws;      // attempt the conversion
  if (ss.eof()) return result;  // success
  return {};                    // failure
}

Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.

Here is an example of using it:

int n;
std::cout << "n? ";
{
  std::string s;
  getline( std::cin, s );
  auto x = string_to <int> ( s );
  if (!x) return complain();
  n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";

limitations and type identification

In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.

The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.

like image 26
Dúthomhas Avatar answered Sep 29 '22 13:09

Dúthomhas


There is a function in c called isdigit(). That will suit you just fine. Example:

int var1 = 'h';
int var2 = '2';

if( isdigit(var1) )
{
   printf("var1 = |%c| is a digit\n", var1 );
}
else
{
   printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digit\n", var2 );
}
else
{
   printf("var2 = |%c| is not a digit\n", var2 );
}

From here

like image 41
nook Avatar answered Sep 29 '22 14:09

nook


If istream fails to insert, it will set the fail bit.

int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
    std::cout << "I failed, try again ..." << std::endl
    std::cin.clear(); // reset the failed state
}

You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.

For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly

like image 31
Zac Howland Avatar answered Sep 29 '22 12:09

Zac Howland