Java to C++ syntax

139 views Asked by At

C++ beginner here. Wondering what the syntax is for this piece of Java code on restricting user input. Here is an example of a Java code I wrote

while (!in.hasNext("[A-Za-z]+")){}

Where "in" is my scanner variable. This piece of code runs when the input is not a real number, and returns an error message with the option to enter something in again. I haven't been able to find the equivalent of this "range" condition on C++. Any help would be appreciated.

EDIT: I have tried using the regex function in Dev C++ but it gives me a warning like this:

 #ifndef _CXX0X_WARNING_H
 #define _CXX0X_WARNING_H 1

 #if __cplusplus < 201103L
 #error This file requires compiler and library support for the \
 ISO C++ 2011 standard. This support is currently experimental, and must be \
 enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #endif

 #endif

Does this mean that I cant use the regex function in Dev C++?

2

There are 2 answers

0
NathanOliver On

If you wan to loop until you get a real number then you can use:

do
{
    cin >> input;
} while(std::regex_match (input, std::regex("[A-Za-z]+")));

You can also use std::stod() to convert a std::string to a double. Doing that will make sure you are getting a valid real number since a number and have e/E in it. You can do that with:

std::string input;
double value;
size_t pos;
do
{
    cin >> input;
    value = stod(input, &pos);
} while (pos < input.size());
0
Jayesh Chandrapal On

Example:

cin >> inputStr;
if (std::regex_match (inputStr, std::regex("[A-Za-z]+") )) {
    // do something, will you ?
}

Note: you will need to include <regex>.

More info: http://www.cplusplus.com/reference/regex/regex_match/