阅读价格(例如89.95美元)到双倍

Ros*_*ell 3 c++

我正在进行一项任务,要求我从txt文件中读取数据.数据字段用于书籍,因此我有标题,书籍ID,价格,数量.除了阅读价格外,一切都运作良好.我正在使用atof(),当我从价格前面移除'$'符号时,它会工作,但当'$'存在时返回'0'.

如何让它忽略'$'?

txt文件的一个示例:

Introduction to programming languages
1
$89.99
100
Run Code Online (Sandbox Code Playgroud)

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

Whi*_*TiM 11

你看,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;
}
Run Code Online (Sandbox Code Playgroud)

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

    ......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;
}
Run Code Online (Sandbox Code Playgroud)