编译后程序崩溃

时间:2014-03-05 17:28:31

标签: c++ loops crash

我正在为我的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

2 个答案:

答案 0 :(得分:2)

char* pass = "";

在这里,您声明了一个指向字符串文字的指针,这是一个字符数组,占据了您不允许修改的存储区域。遵循C ++ 11标准的最新编译器应该为此行产生错误,因为字符串文字不再可以隐式转换为char*,而是改为const char*

当您在此行std::cin >> pass;中修改此内存时,您的程序具有未定义的行为并且所有投注均已关闭。崩溃只是可能的结果之一。

接下来,您无法比较这样的字符串:

pass != "y"

pass是一个指针,"y"衰减到一个。你不是在这里比较字符串的内容,而是指针值永远不会相同。

忘记指针,直到你准备好解决它们,改为使用std::string类。然后比较字符串就像str1 == str2一样简单。

答案 1 :(得分:1)

while (pass != "n")

pass是指针,因此如果您想要获得其价值,则应使用*passpass[0]

除了看@Borgleader评论

编辑:

char pass*;更改为std::string pass; - 它应解决问题。