从字符串转换为double和int-C ++

时间:2019-12-21 07:11:39

标签: c++ string

我想知道如何转换3 x^ 2(文本用空格给出) 到double c = 3int d = 2

我的解决方案

istream & operator>> (istream & in, Monomial &m) {
    char dummy1, dummy2;
    in>> m.coefficient >> dummy1 >> dummy2>> m.degree;
    return in;
}

适用于3x^2,但不适用于1x1

输入看起来像

1
2
1x
2x
3x^2
3 x^ 3

每行的系数应为第一个数字,度数为最后一个数字。

3 个答案:

答案 0 :(得分:1)

如果您的输入将采用相同的格式** A x * B **,那么我建议使用STL,这就是您main()的样子:

int main() {

    std::string equation = "233 X^ 36";
    std::string delimiter = " ";
    std::string tmp;

    tmp = equation.substr(0, equation.find(delimiter));
    double duble = std::stod(tmp);

    tmp = equation.substr(equation.rfind(delimiter));
    int integer = std::stoi(tmp);

    std::cout<< duble << " " << integer << std::endl;

    return 0;
 }

这是一个伪代码,但我希望它足以使我的观点清楚。

答案 1 :(得分:1)

  1. 您要阅读的内容不太简单
  2. 了解有关 Recursive Descent Parsers 的信息。
  3. 如果您命名输入令牌,则您具有: enum token_t { tk_number, tk_x, tk_xcaret, tk_end };(到达流的末尾时将使用tk_end。)
  4. 您的输入可以描述为以下几行之一:

    tk_end // empty input
    tk_number
    tk_number tk_x
    tk_number tk_xcaret tk_number
    
  5. 您必须解决两个问题:
    • 如何从字符to tokens
    • 转换输入
    • 一旦您能够将输入作为令牌读取,如何检查正确的 order of tokens

请参见下面的分词器以解决您的问题。

欢迎您,祝您好运!

enum token_t { tk_end, tk_number, tk_x, tk_xcaret };

double number;

token_t get_token(istream& is )
{
  ws(is); // skip white-spaces

  switch (is.peek()) // what's the next character?
  {

  case EOF:
    return tk_end; // end of stream reached

  case 'x':
    is.get(); // skip x
    if ('^' != is.peek())
      return tk_x;
    else
      return is.get(), tk_xcaret; // skip ^ and return

  default:
    if (!(is >> number))
      throw "number expected";
    return tk_number;

  }
}

答案 2 :(得分:0)

使用regular expressions的简单解决方案:

std::pair<double, int> parse(const std::string& str) {
    static const std::regex regex(
        R"#(\s*(\d+(?:\.\d+)?)(\s*x(?:\^\s*(\d+))?)?\s*)#");

    std::smatch match;
    if (std::regex_match(str, match, regex)) {
        if (match[2].matched) {
            if (match[3].matched)
                return {std::stod(match[1].str()), std::stoi(match[3].str())};
            else
                return {std::stod(match[1].str()), 1};
        }
        else
            return {std::stod(match[1].str()), 0};
    }

    throw std::invalid_argument{"Bad expression"};
}

int main() {
    auto p1 = parse("1.2");
    std::cout << p1.first << ' ' << p1.second << std::endl;     // 1.2 0

    auto p2 = parse("3.4 x");
    std::cout << p2.first << ' ' << p2.second << std::endl;     // 3.4 1

    auto p3 = parse("5.6 x^ 78");    
    std::cout << p3.first << ' ' << p3.second << std::endl;     // 5.6 78
}

我对\d+(?:\.\d+)?使用了简单表达式double,对\d+使用了int。您可能需要将它们调整为特定的输入格式。