2014-03-05 154 views
0

我正在爲我的C++類寫一個程序,似乎無法找出與我的代碼是什麼問題。代碼編譯但是導致程序在第16行之後崩潰,我無法弄清楚。程序崩潰後編譯

#include <iostream> 

// Declare Global variables and Prototyping 
int const TAX = .07; 
float inputStickerPrice(); 

int main() 
{ 
    float totalStickerPrice = 0.0, discount = 0.0, totalPrice = 0.0; 
    char* pass = ""; 

// Calculate the total sticker price 
    while (pass != "n") 
    { 
     totalStickerPrice += inputStickerPrice(); 
     std::cout << "Would you like to enter another item? [y/n] "; 
     std::cin >> pass; 

// Pass validation Loop 
     while (pass != "y" && pass != "n") 
     { 
      std::cout << "INVALID INPUT. Please enter y for yes or n for no. "; 
      std::cin >> pass; 
     } // End of Pass Loop 

    } // End of Sticker Price Loop 

// Input Discount 
    while (!(discount >= 0.0 && discount <= 1)) 
    { 
     std::cout << "Please enter the discount: "; 
     std::cin >> discount; 

// Validate input 
     if (!(discount >= 0.0 && discount <= 1)) 
     { 
      std::cout << "INVALID INPUT. Discount must be between 0.0 and 1.0. "; 
     } // End of validation 

    } // End of Discount Loop 

    totalPrice = totalStickerPrice * discount; // Apply Discount to total Sticker Price 
    std::cout << "The Subtotal is: " << totalPrice << std::endl; 
    totalPrice *= (1+TAX); // Apply Tax to Subtotal 
    std::cout << "The Cost after Tax is: " << totalPrice << std::endl; 

    std::cin.get(); 
    return 0; 
} 

//********************** 
// Input sub program * 
//********************** 

float inputStickerPrice() 
{ 
    using namespace std; 
    float sticker = 0.0; 

    cout << "Please input the sticker price of the item: "; 
    cin >> sticker; 

// Validation Loop 
    while(!(sticker >= 0.0 && sticker <= 9999.99)) 
    { 
    cout << "INVALID INPUT. Please input a value between 0 and 9999.99: "; 
    cin >> sticker; 
    } // End of Validation Loop 

    return sticker; 

} // End of Input Function 
+0

您正在嘗試讀取字符串litteral。 – Borgleader

回答

2
char* pass = ""; 

這裏您聲明瞭一個指向字符串文字的指針,這是一個字符數組,它佔據了一個不允許修改的存儲區域。最近遵循C++ 11標準的編譯器應該爲這一行產生一個錯誤,因爲字符串文字不再可以隱式轉換爲char*,而是轉換爲const char*

當您在此行修改此內存std::cin >> pass;您的程序有未定義的行爲,並且所有投注都關閉。碰撞只是可能的結果之一。

接下來,你不能比較字符串這樣的:

pass != "y" 

pass是一個指針和"y"衰變到一個。你不在這裏比較字符串的內容,但是指針值永遠不會相同。

忘記指針直到你準備好解決它們,請使用std::string類。然後比較字符串就像str1 == str2一樣簡單。

1
while (pass != "n") 

pass是一個指針,所以你應該使用*passpass[0]如果你想obain它的價值。

除了看@Borgleader評論

編輯:

變化char pass*;std::string pass; - 它應該解決這個問題。

+0

這不會導致程序崩潰。事實上,這將永遠是真實的,因爲他比較了兩種不同的字符串字體的地址。 – Borgleader

+0

對,我太快了,想不起來。我會解決這個問題。 –