开发者

checking user input for right value in C++

I have a requirment that accepts values from user input. It can be integers or strings. User input i开发者_JAVA技巧s accepted as below.

string strArg;
cout << "Enter price value "  << endl;
std::getline(std::cin, strArg);
int input;
std::stringstream(strArg) >> input;

Question is how do i check user has entered integer, rather than string, i.e., check for right input. How can we do this in portable way in C++? As in my project Boost is not allowed as my manager is not happy in using it:)


Something like this ought to do:

#include <iostream>
#include <sstream>
#include <string>

int main(void)
{
  std::cout << "input:" << std::endl; 
  std::string input;
  std::getline(std::cin, input);

  std::istringstream str(input);
  int iv = 0;
  // this checks that we've read in an int and we've consumed the entire input, else
  // treat as string.
  if (str >> iv && str.tellg() == input.length())
  {
    std::cout << "int: " << iv << std::endl;
  }
  else
  {
    std::cout << "string: " << input << std::endl;
  }     

  return 0;
}


There is no real reason to go through stringstream except you do not need to clear it if the user enters something invalid, plus you can echo it back to them..

int arg;
while(! (cin >> arg) )
{
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n');

   // tell the user their value was invalid
}

// now we have a valid number

If you allow the user to enter integers or strings but just behave differently when it is a string you can of course use istringstream.

Note that you may wish to check your stream is empty after reading the number in case the user entered 123XYZ which if you just streamed in would be considered "valid" as it starts with an integer.


Use std::stringstream and operator>> and check if the conversion was successful.


Something like this:

#include <iostream>
#include <sstream>


int main()
{
    std::stringstream ss;

    ss << "1234";

    int a = 0;
    ss >> a;
    if ( ss.fail() )
    {
        std::cout << "it is not a number" << std::endl;
    }
    else
    {
        std::cout << a << std::endl;
    }
}


boost::lexical_cast is apprximately the same as doing:

std::stringstream i; i << strArg;
int k; i >> k;


You may use regular expressions to check it. As far as I know, new C++ standart has support of regular expressions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜