我试图用正则表达式来搜索像#34; long tonne"忽略" long"之间的任何空格。和#34; tonne",我认为最好用正则表达式。使用下面的代码,它将打印出每个转换后的输出,但我只是尝试打印一个结果。恩。如果我输入12公斤,我只希望我的结果打印转换为lbs字符串。
到目前为止,我尝试过:
通过在另一个项目中复制和粘贴来逐段运行代码(我感觉它是我遇到问题的正则表达式)
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
cout << "Enter your mass with unit: ";
double earthMass;
string unit;
string tolower(unit);
cin >> earthMass >> unit;
regex kg("kg|kgs");
if (regex_match("kg", kg))
{
double dKgToLb;
dKgToLb = (earthMass * 2.20462);
cout << "your converted mass is : " << dKgToLb << " lb" << endl;
}
regex pound("lb|lbs");
if (regex_match("lb", pound))
{
double dLbToKg;
dLbToKg = (earthMass * 0.453592);
cout << "your converted mass is : " << dLbToKg << " kg" << endl;
}
regex longTonne("long\\s*tonne|lg\\s*tn");
if (regex_match("long tonne", longTonne))
{
double dLongToShort;
dLongToShort = (earthMass * 1.12);
cout << "your converted mass is : " << dLongToShort << " sh tn" << endl;
}
regex shortTonne("short\\s*tonne|sh\\s*tn");
if (regex_match("short tonne", shortTonne))
{
double dShortToLong;
dShortToLong = (earthMass * 0.892857);
cout << "your converted mass is : " << dShortToLong << " lg tn" << endl;}
}
else if (!cin.good())
{
cerr << "your input is invalid\n";
return EXIT_FAILURE;
}
}