-1

I try to identify if a number is an interger or not.

  1. When I run this, I enter a number, such as 5.5, it shows "5.5 is not int. Please try again: ". Then I enter the letter, such as 'a', it shows "5.5 is not int. Please try again: ". The letter 'a' is a character, not integer, I think it should go to the second case and must show "No letter please", but it isn't.

  2. When I first enter a letter, such as 'D', the program run "Please no letter" unlimited times. I wants it shows "Please no letter" but only once, then I can enter another number in this loop.

How can I fix these errors?

while (true) {


    while ((num) != static_cast<int>(num)) {
        cout << "\t" << num << " is not int. Please try again: ";
        cin >> num;
        cin.clear();
        cin.ignore(80, '\n');

    }
    while (!(cin >> num)) {
        cout << "\tNo letter please: ";
        cin >> num;
        cin.clear();
        cin.ignore(80, '\n');

    }
    cout << "Good! " << num << " is an int!\n\n";

}

symta
  • 15
  • 4
  • Oh my.. No matter what you will run indefinitely. `while(true)` and no way out.. – Gavin Oct 26 '16 at 15:51
  • You fix this with a [debugger](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) - step through the code, look at the variables and you'll understand how everything is working when you're done. – UKMonkey Oct 26 '16 at 15:54
  • Well, you've described how it currently runs, but you have not described how you would like for it to run. Edit your question and tell us clearly the behavior you are trying to produce. – Alyoshak Oct 26 '16 at 19:09
  • @Alyoshak thanks, I just described it little bit more, is it more clear? And if yes, can you explain why it has errors? – symta Oct 26 '16 at 19:16
  • What is the type of number? cin>>num will never change the type of num. What should your code do? – Klamer Schutte Oct 26 '16 at 19:20

2 Answers2

0

You can do in this way. Enter a string from user. Count the number of characters in that string. If that is equal to string length it is a valid positive integer. For negative integers just check if the number of digits is one less than size of string and string is starting with 0.

#include <iostream>
using namespace std;

int main() 
{
string s;
while(true)
{
    cin>>s;
    int i,no_of_digits=0;
    for(int i=0;i<s.length();i++)
    {
        if(isdigit(s[i]))
            no_of_digits++;
    }
    if(no_of_digits == s.length() || (no_of_digits == s.length()-1 && s[0]=='-'))
    {
        cout<<"Good "<<s<<" is an Integer.";
        break;
    }
    cout<<s<<" is not a valid Integer!\nPlease Enter again\n";
}
return 0;
}
Ishpreet
  • 5,230
  • 2
  • 19
  • 35
0

The best way to parse string in cpp. It's to use stringstream or use sto* series functions of cpp11.

There are already some good answer here.

Community
  • 1
  • 1
Stargateur
  • 24,473
  • 8
  • 65
  • 91