【问题标题】:Java to C++ syntaxJava 到 C++ 语法
【发布时间】:2015-08-28 13:58:46
【问题描述】:

这里是 C++ 初学者。想知道这段 Java 代码限制用户输入的语法是什么。这是我编写的Java代码示例

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

“in”是我的扫描仪变量。这段代码在输入不是实数时运行,并返回一条错误消息,其中包含再次输入内容的选项。我无法在 C++ 上找到这个“范围”条件的等价物。任何帮助将不胜感激。

编辑: 我曾尝试在 Dev C++ 中使用 regex 函数,但它给了我这样的警告:

 #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

这是否意味着我不能在 Dev C++ 中使用 regex 函数?

【问题讨论】:

  • 您可以在 C++ 中搜索 正则表达式(或正则表达式)。
  • 这是什么意思??
  • 您所说的“范围条件”只是一个正则表达式,大多数编程语言都可以使用它。在 C++ 中使用它们有很多信息。

标签: java c++ input while-loop user-input


【解决方案1】:

如果你想循环直到你得到一个实数,那么你可以使用:

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

您还可以使用std::stod()std::string 转换为double。这样做将确保您从一个数字中获得一个有效的实数并在其中包含 e/E。你可以这样做:

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

【讨论】:

    【解决方案2】:

    示例:

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

    注意:您需要包含&lt;regex&gt;

    更多信息: http://www.cplusplus.com/reference/regex/regex_match/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多