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

标签 c++ string stream extract stringstream

我正在用 C++ 制作一个自然语言计算器。用户将输入一行字符串进行计算。该程序将提取数字和操作并相应地应用它。以下是我的部分代码

#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;
}

如果用户以正确的格式输入,即加 2 和 3,12 减 8,程序将成功运行。 但问题是在两种情况下

  1. 如果用户以其他格式输入,例如“7 加 6”。
  2. 即使格式正确但只有一个数字“25 的平方根”。

有没有一种解决方案可以提取 float 而不考虑 float 的位置或数量?

谢谢

最佳答案

如果你想做的是从字面上提取float,你可以利用std::stof这一事实。还可以返回它离开的地方,你可以用它来确定整个“单词”是否是一个float(例如“6c”)并捕获单词的invalid_argument绝对不是 float (例如“加号”):

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;
}

由此,getFloats("7 plus 6") 产生 {7, 6}getFloats("square root of 25") 产生 {25}

关于c++ - 从c++中的一行字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29607308/

相关文章:

c++ - 最优雅的可变函数

python - 返回包含文本值的列的列名

c++ - stdin、stdout 和 stderr 是文件吗?

c# - 从流开始进程

python - 在 Cython 中包装返回复杂类型 Vector 的函数

c++ - 如何使用 C++ 流输出小数点后 3 位数字?

c++ - 从编译器的角度来看,传递 const 值或 const ref 之间的区别

c++ - 我如何摆脱此错误main.cpp :43:19: error: no viable overloaded '=' novowels[100] = remove(name[100]);

Java Process Builder 命令错误,转义双引号

c++ - ios::ate 不会移动到文件末尾