0

所以这个例子是我想从我的函数中得到的,但我无法让 atof 工作,因为我不断收到“错误:无法将参数 '1' 转换为 'std::basic_string' to 'const char*' to '双 atof(const char*)'"。有人可以向我解释我做错了什么吗?

发票2.txt:

hammer#9.95
saw#20.15
shovel#35.40

程序:

/* 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;
}
4

1 回答 1

4

atof需要一个指向 a 的指针const char,然后你给它一个string. 为了使其工作,您必须使用其c_str()上的方法将字符串转换为 char 表。

于 2013-11-11T00:17:22.750 回答