C ++输入文件字符串浮动错误

时间:2013-11-11 00:14:23

标签: c++

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

Invoice2.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;
}

1 个答案:

答案 0 :(得分:4)

atof需要指向const char的指针,并为其指定string。为了使其工作,您必须使用c_str()方法将字符串转换为char表。