簡體   English   中英

C ++輸入文件字符串浮動錯誤

[英]C++ input file string to float error

因此,該示例就是我想從函數中獲取的內容,但是我無法獲得atof的作用,因為我不斷收到“錯誤:無法將參數'1'的'std :: basic_string'轉換為'const char *'到' 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;
}

atof需要一個指向const char的指針,然后給它一個string 為了使其工作,您必須使用c_str()方法將字符串轉換為char表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM