c – 将价格(例如89.95美元)读入双倍
发布时间:2020-12-16 10:12:50 所属栏目:百科 来源:网络整理
导读:我正在进行一项任务,要求我从txt文件中读取数据. 数据字段用于书籍,因此我有标题,书籍ID,价格,数量. 除了阅读价格外,一切都运作良好.我正在使用atof(),当我从价格前面移除’$’符号时,它会工作,但当’$’存在时返回’0′. 如何让它忽略’$’? txt文件的一个
|
我正在进行一项任务,要求我从txt文件中读取数据.
数据字段用于书籍,因此我有标题,书籍ID,价格,数量. 除了阅读价格外,一切都运作良好.我正在使用atof(),当我从价格前面移除’$’符号时,它会工作,但当’$’存在时返回’0′. 如何让它忽略’$’? txt文件的一个示例: Introduction to programming languages 1 $89.99 100 到目前为止,这是我的代码: #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;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读
