2014-03-05 62 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

对,我太快了,想不起来。我会解决这个问题。 –