gpt4 book ai didi

c++ - 使用 money_get<> 解析 USD 和 $ 金额时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:52 25 4
gpt4 key购买 nike

我在使用 money_get<> 解析 USD 和 $ 金额时遇到错误。

#include <iostream>         /// cin, cout
#include <locale>
#include <iterator>

using namespace std;


int main()
{
cin.imbue(std::locale("en_US.UTF-8"));

std::cout << "USD 1.11$2.22"
<< " parsed with the facet directly: ";

auto& f = std::use_facet<std::money_get<char>>(cin.getloc());
std::ios_base::iostate err;
std::istreambuf_iterator<char> frm(cin), end;
long double val;

/// international currency symbol
frm = f.get(frm, end, true, cin, err, val);
std::cout << "\n "<< val/100;

string str;
cin >> str;
cout << "\n remaining: " << str << endl;

/// local currency symbol
f.get(frm, end, false, cin, err, val);
std::cout << "\n "<< val/100;
}

http://coliru.stacked-crooked.com/a/b1f76385cbed6834

输入是:

USD  1.11
$2.22

输出是:

USD  1.11$2.22 parsed with the facet directly: 
1.11
remaining: .22
0

来自相应 moneypunct<> 方面的模式是: 对于美元:符号空间值 对于 $: sign symbol value none

显然,当读取第一个数量时,我超出了标记。我不知道为什么。谢谢。

最佳答案

我进一步隔离了问题。

这似乎不是 get_money() 操纵器或 money_get<> 方面的问题。

这是字符串 v/s cin 的问题 - 使用本地货币(例如:$)指定的货币金额的输入在 istringstream 中工作正常,但在 cin 中不工作。

请注意,我已经修改了来自 cppreference.com 的以下部分代码。

http://coliru.stacked-crooked.com/a/19e0fdc663c5d845

使用本地货币(例如:$)指定的货币金额输入在 istringstream 中正常工作:

string str = "$1.11 $2.22 $3.33 4.44 5.55";


void stringInput() /// works
{
cout << "string Input ... works:\n";

istringstream s1(str);
s1.imbue(locale("en_US.UTF-8"));

cout << fixed << setprecision(2);
cout << '"' << str << "\" parsed with the I/O manipulator: ";

long double val;

while(s1 >> get_money(val))
cout << val/100 << ' ';

cout << "\n";
}

输出:

string Input ... works:
"$1.11 $2.22 $3.33 4.44 5.55" parsed with the I/O manipulator: 1.11 2.22 3.33 4.44 5.55

使用本地货币(例如:$)指定的货币金额输入在 cin(相同链接)中不正确:

void cinInput()             /// does not work
{
cout << "cin Input ... doesn't work:\n";

cin.imbue(locale("en_US.UTF-8"));

cout << fixed << setprecision(2);
cout << '"' << str << "\" parsed with the I/O manipulator: ";

long double val;

while(cin >> get_money(val))
std::cout << val/100 << ' ';
cout << '\n';
}

输出:

cin Input ... doesn't work:
"$1.11 $2.22 $3.33 4.44 5.55" parsed with the I/O manipulator: 0.11 0.22 0.33 0.44 0.55

关于c++ - 使用 money_get<> 解析 USD 和 $ 金额时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48302667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com