简体   繁体   English

从C ++中的一行字符串中提取数字

[英]Extract numbers from a line of string in c++

I am making a natural language calculator in C++. 我正在用C ++编写自然语言计算器。 The user will input a line of string for calculation. 用户将输入一行字符串以进行计算。 The program will extract the numbers and the operation and apply it accordingly. 该程序将提取数字和运算并相应地应用它。 Following is part of my code 以下是我的代码的一部分

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

int main()
{
    string inp;
    float n1,n2;
    string s1,s2;

    cout<<"Enter your string"<<endl;
    getline(cin,inp);

    stringstream ss;
    ss.str(inp);

    ss>>s1>>n1>>s2>>n2;
}

The program will run successfully if the user enters in correct format ie Add 2 and 3, Subtract 8 from 12. But the problem is in two cases 如果用户以正确的格式输入该程序,则该程序将成功运行,即加2和3,从12中减去8。但是问题出在两种情况下

  1. If the user enters in some other format like "7 plus 6". 用户输入的其他格式,例如“ 7加6”。
  2. Even in the correct format but only one number "square root of 25". 即使采用正确的格式,也只有一个数字“ 25的平方根”。

Is there a solution which can extract the floats regardless of the position or number of floats? 有没有一种解决方案可以不考虑浮标的位置或数量而提取浮标?

Thanks 谢谢

If what you want to do is literally extract the float s, you can take advantage of the fact that std::stof can additionally return where it leaves off, which you can use to determine if the entire "word" is a float (eg for "6c") and catch the invalid_argument for words that are definitely not floats (eg for "plus"): 如果您想做的是从字面上提取float ,则可以利用以下事实: std::stof可以另外返回它离开的地方,可以用来确定整个“单词”是否为float (例如代表“ 6c”),并为无效的单词捕获invalid_argument (例如,“ plus”代表):

std::vector<float> getFloats(const std::string& s) {
    std::istringstream iss(s);
    std::string word;
    std::vector<float> result;

    size_t pos = 0;
    while (iss >> word) {
        try {
            float f = std::stof(word, &pos);
            if (pos == word.size()) {
                result.push_back(f);
            }   
        }   
        catch (std::invalid_argument const& ) { 
            // no part of word is a float
            continue;
        }   
    }   

    return result;
}

With that, getFloats("7 plus 6") yields {7, 6} and getFloats("square root of 25") yields {25} . 这样, getFloats("7 plus 6")产生{7, 6} getFloats("square root of 25") {7, 6}getFloats("square root of 25")产生{25}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM