我正在做一项作业,要求我从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 ++中读取金钱。 std::get_money
你可以这样做:
#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, 50);
cout << "Title : " << title << endl;
filein.getline(strBookid, 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;
}
作为第二种选择,您可以修改原始代码以$
手动测试符号...(请参见下面的代码段)
......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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句