c – 将价格(例如89.95美元)读入双倍

c – 将价格(例如89.95美元)读入双倍,第1张

概述我正在进行一项任务,要求我从txt文件中读取数据. 数据字段用于书籍,因此我有标题,书籍ID,价格,数量. 除了阅读价格外,一切都运作良好.我正在使用atof(),当我从价格前面移除’$’符号时,它会工作,但当’$’存在时返回’0′. 如何让它忽略’$’? txt文件的一个示例: Introduction to programming languages1$89.99100 到目前为止,这是 我正在进行一项任务,要求我从txt文件中读取数据.
数据字段用于书籍,因此我有标题,书籍ID,价格,数量.
除了阅读价格外,一切都运作良好.我正在使用atof(),当我从价格前面移除’$’符号时,它会工作,但当’$’存在时返回’0′.

如何让它忽略’$’?

txt文件的一个示例:

Introduction to programming languages1.99100

到目前为止,这是我的代码:

#include <iostream>#include <fstream>#include <string>#include <cstdlib>       using namespace std;int main() {    char Title[50];    char strBookID[10];    char strPrice[10];    char strAmount[10];    int bookID;    double price;    int amount;    ifstream filein("bookfile.txt");    filein.getline(Title,50);    cout << "Title : " << Title << endl;    filein.getline(strBookID,10);    cout << "BookID as a string : " << strBookID << endl;    filein.getline(strPrice,10);    cout << "Price as a string : " << strPrice << endl;    filein.getline(strAmount,10);    cout << "Qty as a string: " << strAmount << endl;    bookID = std::atoi(strBookID);    cout << "The Book ID as an int : " << bookID << endl;    price = std::atof(strPrice);    cout << "The price as a double : " << price << endl;  return 0;}
解决方法 你看,C标准背后的人们喜欢金钱而他们知道我们都这么做,所以他们提出了一个很好的方式来在C语言中以通用的方式阅读金钱.

你可以这样做:

#include <iostream>#include <fstream>#include <string>#include <cstdlib>   #include <locale>    //add this    using namespace std;int main() {    char Title[50];    char strBookID[10];    char strPrice[10];    char strAmount[10];    int bookID;    long double price;   //changed! get_money only supports long double    int amount;    ifstream filein("bookfile.txt");    filein.getline(Title,10);    cout << "BookID as a string : " << strBookID << endl;    filein.imbue(std::locale("en_US.UTF-8"));      /// added    filein >> std::get_money(price);               ///changed    price /= 100;         //get_money uses the lowest denomination,in this case cents,so we convert it $by divIDing the value by 100    cout << "Price as a string : $" << price << endl;    ///changed    filein.getline(strAmount,10);    cout << "Qty as a string: " << strAmount << endl;    bookID = std::atoi(strBookID);    cout << "The Book ID as an int : " << bookID << endl;    price = std::atof(strPrice);    cout << "The price as a double : " << price << endl;  return 0;}

作为第二种选择,您可以修改原始代码以手动测试$sign …(请参阅下面的代码段

......many lines skipped ...........    bookID = std::atoi(strBookID);    cout << "The Book ID as an int : " << bookID << endl;    price = std::atof(strPrice[0] == '$' ? strPrice+1 : strPrice );   //modifIEd    cout << "The price as a double : " << price << endl;  return 0;}
总结

以上是内存溢出为你收集整理的c – 将价格(例如89.95美元)读入双倍全部内容,希望文章能够帮你解决c – 将价格(例如89.95美元)读入双倍所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1218417.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存