Reputation: 15
I am writing a program for my C++ class and can't seem to figure out what the problem with is with my code. The code compiles but something causes the program to crash after line 16 that I just can't figure out.
#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
Upvotes: 0
Views: 56
Reputation: 55415
char* pass = "";
Here you declared a pointer to a string literal, an array of characters which occupies a region of storage that you're not allowed to modify. Recent compilers that follow C++11 standard are supposed to produce an error for this line, because string literals are not implicitly convertible to char*
anymore, but to const char*
instead.
When you modify this memory in this line std::cin >> pass;
your program has undefined behaviour and all bets are off. A crash is just one of possible outcomes.
Next, you can't compare strings like that:
pass != "y"
pass
is a pointer and "y"
decays to one. You're not comparing contents of string here, but pointer values that will never be the same.
Forget about pointers until you're ready to tackle them, use std::string
class instead. Then comparing strings will be as easy as str1 == str2
.
Upvotes: 2
Reputation: 27595
while (pass != "n")
pass
is a pointer, so you should use *pass
or pass[0]
if you want to obain its value.
Besides look at @Borgleader comment
EDIT:
Change char pass*;
into std::string pass;
- it should fix the issue.
Upvotes: 1