我正在用 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,程序将成功运行。 但问题是在两种情况下
- 如果用户以其他格式输入,例如“7 加 6”。
- 即使格式正确但只有一个数字“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/