1

I am facing difficulty while checking the integer number. If user enters only character or only special character or only integer or any special character before integer I'm able to find it but in case of special character after the integer is not handling. so any one please help me out.

port:cout << "Enter the port number:" << endl;
cin  >> nPort;
if(!cin)
{ 
    cout << "Invalid Port Number" << endl;
    cin.clear();
    cin.ignore(MAX_SIZE,'\n');
    goto port;
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 6
    Read the whole line into a string. Extract the number from the string. Ignore the remainder of the string. – Some programmer dude Feb 01 '19 at 07:55
  • 1
    Not an exact duplicate as this question is about doubles, but this answer should work equally fine for integers: https://stackoverflow.com/a/27004240/3807729 – Galik Feb 01 '19 at 08:09
  • Possible duplicate of [Good input validation loop using cin - C++](https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) – Gelldur Feb 01 '19 at 08:32
  • Possible duplicate of [How to check if cin is int in c++?](https://stackoverflow.com/questions/27003967/how-to-check-if-cin-is-int-in-c) – Duck Dodgers Feb 01 '19 at 08:37

2 Answers2

0

I considered the linked other posts not exactly spot-on.

The following code will read the input string. If there is some non-numeric tokens after the number, they will be ignored. In any case, the whole input string will be read, so that cin is empty afterwards. If there are some non-numeric inputs before the number, the whole operation fails.

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    cout << "enter number: ";
    int port;
    string readLine;
    getline(cin, readLine);

    stringstream reader(readLine);

    if(reader >> port)
    {
        std::cout << "Port is " << port;
    }
    else
    {
        std::cout << "Invalid input!";
    }

    return 0;
}
IceFire
  • 4,016
  • 2
  • 31
  • 51
0

First, you have to verify whether the input provided for the variable nPort is an integer or not and if integer it should be in the port range.

#include<iostream>
#include<iterator>
#include<string>
using namespace std;

bool is_number(string &port){
    string::iterator it = port.begin();
    while(it!=port.end() && isdigit(*it)) it++;
    return !port.empty() && it == port.end();
}

int main() {
    string nPort;
    cin >> nPort;
    if(is_number(nPort) && stoi(nPort)<=65535) cout << "Port Valid" << endl;
    else cout << "Port invalid" << endl;
    return 0;
}