So the example is what I want to get from my function, but I can't get atof to work because I keep getting " error: cannot convert 'std::basic_string' to 'const char*' for argument '1' to 'double atof(const char*)'". Can someone explain to me what I'm doing wrong?
Invoice2.txt:
hammer#9.95
saw#20.15
shovel#35.40
Program:
/* EXAMPLES: *** Invoice ***
----------------------------
hammer $9.95
saw $20.15
shovel $35.40
----------------------------
3 items: $65.50
*/
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
using namespace std;
// Accepts: N/A
// Returns: 0 if no error
int main(void){
int totalItems, position;
double totalPrice, price;
string line, name;
ifstream inputFile("invoice2.txt");
cout << "*** Invoice ***" << endl << "----------------------------" <<
endl;
totalItems = 0;
do{
position = line.find('#');
name = line.substr(0, position);
price = atof(line.substr(position+1, line.length()));
cout << name << "\t\t\t$" << price << endl;
totalItems += 1;
totalPrice += price;
} while (getline(inputFile, line));
cout << "----------------------------" << endl;
cout << " " << totalItems << ":\t\t\t$" << totalPrice << endl;
return 0;
}
atof
requires a pointer to a const char
, and you give it a string
. In order to make it work, you have to convert a string to a char table using the c_str()
method on it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.