0

my code is:

int num;
string check = "true";
cin >> num;
if (cin.fail())
        check = "false";

cout << check;
}

I want to make sure the input is an integer only. When the input is like r3 (non-digits followed by integer), the output is false. But when the input is like 3r (digits followed by non-digits), the output is true. How to solve this problem?

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
Nino
  • 11
  • 3

3 Answers3

1

You can take input as a string and then check if the string is a number:

#include <iostream>
#include <string>
#include <cstdlib>

int main()
{
    std::string nstr;
    long n;
    char *end_point;
    std::cin >> nstr;
    n = std::strtol(nstr.c_str(), &end_point, 10);
    std::cout << (*end_point == '\0' ? "true" : "false") << '\n';
}
mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
0

You have to only check first character if it is a digit:

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string s;
    std::cin >> s;
    std::cout << (isdigit(s[0]) ? "true" : "false") << "\n";
}
$ ./a.out 
123
true
$ ./a.out 
r1
false
$ ./a.out 
1r
true

If you would like to include signed numbers to yours test:

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string s;
    std::cin >> s;

    bool unsigned_int = isdigit(s[0]);
    bool signed_int = (s[0] == '-' || s[0] == '+') && isdigit(s[1]);

    std::cout << (unsigned_int || signed_int ? "true" : "false") << "\n";
}
$ ./a.out 
123
true
$ ./a.out 
+1xyz
true
$ ./a.out 
-98xxx
true
$ ./a.out 
abc
false
Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28
0
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int num;
    string input;
    string check = "true";

    cin >> input;
    if (input.length() != to_string(num = atoi(input.c_str())).length())
    {
        check = "false";
    }   

    cout << check;
    return 0;
}
secuman
  • 539
  • 4
  • 12