dimanche 19 juin 2016

Reading in a price (eg. $89.95) into a double


I am working on an assignment that requires that I read in data from a txt file. The data fields are for books, so I have a title, book id, price, quantity. Everything is working well except for reading in the price. I am using atof() for that which works when I remove the '$' sign from the front of the price, but returns '0' when the '$' is there.

How do I make it ignore the '$' ?

An example of the txt file:

Introduction to programming languages
1
$89.99
100

Here is my code so far:

#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;
}

Aucun commentaire:

Enregistrer un commentaire