-
switch not working
I have a program here that is supposed to take input in the form of a number and apply it to a switch statement. For some reason no matter what my input is I always get the default case. Any help is appreciated. Thanks.
#include <iostream.h>
#include <iomanip.h>
int main()
{
int prod = 0;
double prod1 = 0;
double prod2 = 0;
double prod3 = 0;
double prod4 = 0;
double prod5 = 0;
cout.setf(ios::left);
cout << " " << setw(15) << "Product" << setw(6) << "Price" << endl;
cout << setw(3) << "\n1. " << setw(15) << "Product 1" << "$2.98" << endl;
cout << setw(3) << "2. " << setw(15) << "Product 2" << "$4.50" << endl;
cout << setw(3) << "3. " << setw(15) << "Product 3" << "$9.98" << endl;
cout << setw(3) << "4. " << setw(15) << "Product 4" << "$4.49" << endl;
cout << setw(3) << "5. " << setw(15) << "Product 5" << "$6.87" << endl;
cout << "\n\nPlease enter the number of the product for every item sold " << endl
<< "Press enter when on the blank line when done." << endl;
while ( (prod = cin.get()) != EOF )
{
switch (prod)
{
case '1':
prod1 += 2.98;
break;
case '2':
prod2 += 4.50;
break;
case '3':
prod3 += 9.98;
break;
case '4':
prod4 += 4.49;
break;
case '5':
prod5 += 6.87;
break;
default:
cout << "This is not a valid entry!" << endl;
break;
}
}
cout << "\nHere is what you got today." << endl;
cout << "Product 1: " << prod1 << endl;
cout << "Product 2: " << prod2 << endl;
cout << "Product 3: " << prod3 << endl;
cout << "Product 4: " << prod4 << endl;
cout << "Product 5: " << prod5 << endl;
return 0;
}
-
prod stores an integer value. '1', '2', '3', etc. are characters.
-
from MSDN:
get(); Extracts a single character from the stream and returns it.
so prod=cin.get(); will return a character and obviously cast that to an int.
so if someone enters 1, then you will get the int value of the ascii char '1' (which is 0x31).... obviously not what you want!!!
so either read in integers rather than chars... or do this:
prod = cit.get() - 0x30
instead.
good luck!
U.
-
This work in C++? Can you use a string in a switch case?
Code:
using System;
class Cpp
{
public static void Main()
{
string array;
Console.Write("Enter the word 'one' or 'two': ");
array = Console.ReadLine();
switch(array)
{
case "one": Console.WriteLine("One is good.");
break;
case "two": Console.WriteLine("Two is good too.");
break;
default: Console.WriteLine("No, Error, SOB!");
break;
}
}
}
-
Troll_King, to answer your question, absolutely not. A switch statement handles a single unit of data, therefore no arrays/pointers can be used in a switch case statement.
Code:
char array[] = "hello world";
switch(array) { //wrong!
//stuff
}
switch(array[0]) { //this is okay
//stuff
}
-
Not in C++ anyway, but you can use strings in C#.