2016-12-15 510 views
-1

我需要從函數返回票證作爲字符串。有一些雙變量,當我將它轉換爲to_string時,它在小數點後顯示6個零。我怎樣才能格式化它,因此它只在小數點後面顯示2個零時,我將該值作爲字符串返回?C++如何將double轉換爲字符串,使其僅在小數點後顯示2位數字?

這裏是我的代碼:

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <string> 

using namespace std; 

static const int NUM_ROWS = 15; 
static const int NUM_SEATS = 30; 
char SeatStructures[NUM_ROWS][NUM_SEATS]; 
double cost; 
double price[NUM_ROWS]; 
int rowRequested, 
seatNumber; 

string PrintTicket(int row, int seat, double cost); 

int main() 
{ 
    ifstream SeatPrices; 

    SeatPrices.open("SeatPrices.dat"); 
    if (!SeatPrices) 
     cout << "Error opening SeatPrices data file.\n"; 
    else 
    { 
     for (int rows = 0; rows < NUM_ROWS; rows++) 
    { 
     SeatPrices >> price[rows]; 
     cout << fixed << showpoint << setprecision(2); 
    } 
    cout << endl << endl; 
    } 
    SeatPrices.close(); 
    cout << "In which row would you like to find seats(1 - 15)? "; 
    cin >> rowRequested; 
    cout << "What is your desired seat number in the row (1 - 30)? "; 
    cin >> seatNumber; 
    cout << PrintTicket(rowRequested, seatNumber, cost); 
    return 0; 
} 
string PrintTicket(int row, int seat, double cost) 
{ 
    return 
    string("\n****************************************\nTheater Ticket\nRow: ") + 
    to_string(row) + 
    string("\tSeat: ") + 
    to_string(seat) + 
    string("\nPrice: $") + 
    to_string(price[rowRequested - 1]) + 
    string("\n****************************************\n\n"); 
} 


/*Data from text file: 
12.50 
12.50 
12.50 
12.50 
10.00 
10.00 
10.00 
10.00 
8.00 
8.00 
8.00 
8.00 
5.00 
5.00 
5.00*/ 
+5

數值類型,如'double'沒有格式化。他們只是價值觀。當你將**這樣一個值轉換爲文本表示時,格式描述了你希望文本表示看起來像什麼。 –

+2

另外,當處理貨幣/貨幣時,你應該使用兩個整數變量。一個用於整個美元,另一個用於美分。這給你一個更適合的固定點類型,因爲你不能有一分之一的分數。 – NathanOliver

+0

我認爲這輪到百分之一的位置,但你可以調整的地方:http://stackoverflow.com/a/25429632/2642059 –

回答

2

使用你std::coutstd::ostringstream使用相同的機械手:

std::string printTicket(int row, int seat, double cost) 
{ 
    std::ostringstream os; 
    os << "\n****************************************\nTheater Ticket\nRow: "; 
    os << row; 
    os << "\tSeat: "; 
    os << seat; 
    os << "\nPrice: $"; 
    os << std::fixed << std::setprecision(2) << cost; 
    os << "\n****************************************\n\n"; 
    return os.str(); 
} 
+0

我以前沒有使用過串流,但工作。謝謝你的幫助 – user131648

相關問題