Switch statement outputs wrong value for cost - c++

When I try to run this code on Microsoft Visual Studio C++; It runs but the value of cost that is being outputted is wrong. Why is that? I do realize that I am not including a default statement, and that I am declaring cost twice, this is because I get the debug error that cost has no declared value, so what I assume is going on is the switch statement is not processing because it some how is not understanding the
cout << "Pizza";
How do I fix this?
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <string>
using namespace std;
int main()
{
int a, b, c, d, e, f, m, p, k, User_Input, Pizza , cost;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
k = 0;
cost = 0;
cout << "What is your favorite vegetarian food from the list below?" << endl;
Sleep(1500);
cout << "Pizza\n";
Sleep(200);
cout << "IceCream\n";
cin >> User_Input;
switch (User_Input)
{
case 1:
cout << "Pizza";
cost = 5;
break;
case 2:
cout << "IceCream";
cost = 5;
break;
}
Sleep(2000);
cout << "The total cost will be: " << cost;
cout << "\n\n\n\t\t\t";
return 0;
}

User_Input is of type "int", you are going to get unexpected results if you try to read a string via cin to that variable. What you probably want to do is either:
read into a string and do a string comparison
read into a string, convert to an int, and do the switch statement
A simplified example:
#include <iostream>
#include <string>
int main()
{
std::string user_input;
int cost = 0;
std::cout << "What is your favorite vegetarian food from the list below?\nPizza\nIceCream\n";
std::cin >> user_input;
if(user_input == "Pizza") {
cost = 5;
} else if (user_input == "IceCream") {
cost = 10;
}
std::cout << "The total cost will be: " << cost << std::endl;
return 0;
}

Related

"noskipws" works but doesn't stop in c++

I am trying to write a program that checks if a phrase is a palindrome or not, and in case nothing is entered or just whitespace, it should print out "empty".
At first, the user should type in the number of phrases that they are going to enter (e.g. 3), and then the phrases that are to be checked.
It works just fine, but when my first input is empty, it prints out "empty" again and again without asking for another phrase.
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int N;
int isPalindromeCounter=0;
int counter = 0;
string inputString;
cin >> N;
cout << "\n";
while (counter<N){
counter++;
cin.ignore(100, '\n');
cin >> noskipws >> inputString;
if (inputString.length()==0){
cout <<"empty\n";
continue;
}
int left = 0;
int right = inputString.length()-1;
if (inputString.length()>20){
cout <<"error\n";
continue;
}
bool isPalindrome = true;
while (left<right){
if (inputString[left] != inputString[right]){
isPalindrome = false;
cout << "no\n";
break;
}
left++;
right--;
}
if (isPalindrome){
cout << "yes\n";
isPalindromeCounter++;
}
}
double percentage = double(isPalindromeCounter)/double(counter)*100;
if (trunc(percentage) != percentage){
cout << setprecision(5) << percentage;
}
else {cout << percentage << ".000" ;}
return 0;
}
What am I doing wrong ?
I expected that it should print "empty" once, and then ask for another input, but it prints "empty" for all the inputs.

How can I count alphabet characters efficiently?

I initialized an array of characters, to put all uppercase and lowercase alphabets.
#include <iostream>
using namespace std;
int main () {
char c;
int cnt = 0;
cout << "Enter 0 to view the results " << endl;
char arr[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
while (1) {
for (int i = 0; i < 100000000; i++)
{
cin >> c;
if (c == arr[i]){
cnt++;
}
else if (c == '0'){
break;
}
else{
cout << "Please enter only characters!" << endl;
}
}
if (c == '0')
break;
}
cout << cnt << endl;
return 0;
}
I know that this code is inefficient.
How to write this code without break;?
If there's a better way to do that without using array, please mention it.
OP's question is very unclear but what I have understood from the comments is OP trying to find a simpler/similar way of counting someone's input for lowercase/upperCase alphabets and keep doing so until the user enters in a 0, I looked online and i found a better way and did some adjustments, it is pretty straight forward, here it is below.
#include <algorithm>
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main()
{
string s = "TEST";
while(s != "0"){
cout << " Enter text: ";
getline(cin, s);
size_t count_alpha = count_if(s.begin(), s.end(),
[](unsigned char ch) { return isalpha(ch); });
cout << "Alphabets: " << ( count_alpha)<<endl ;
}
}

Choosing one of two strings to output?

I was wondering how I could have a program output one of two strings at random.
Hard to explain but this is my example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string age;
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if (0 >= age && age <<= 3)
{
cout << "Oh you're just a baby" << endl;
// OR (random)
cout << "Time to take a nap!" << endl;
}
return 0;
}
I want to program to output either, "Oh, you're just a baby" or "Time to take a nap!" at random whenever the user inputs a number between 0 and 3. Can anybody explain this?
try :
#include <cstdlib>
...
...
...
/* initialize random seed: */
srand(time(NULL));
/* generate secret number: */
int ss = rand() % 2;
if (ss) {
cout << "Oh you're just a baby" << endl;
} else {
cout << "Time to take a nap!" << endl;
}
You can also try this:
take input from user and compare it to random generated value and print output according to it:
#include <iostream>
using namespace std;
int main()
{
int age;
srand(time(NULL));
int a = rand()%3;
cout<<a<<endl; // print the random generated number (between 0 and 3 )
cout << "How old are you?" << endl;
cin >> age;
if (age < 0)
{
cout << "Invalid age" << endl;
}
if(age == a){
cout << "Oh you're just a baby" << endl;
}else{
cout << "Time to take a nap!" << endl;
}
return 0;
}
This uses the STL and only does the random selection from a table, without any user input:
#include <array>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <random>
using std::cout;
using std::endl;
int main(void) {
// The size of the table:
constexpr size_t n = 2;
// A table of insults:
constexpr std::array<const char*, n> insults = {
"Oh, you're just a baby!",
"Time to take a nap."
};
// Boilerplate to initialize a RNG:
const std::default_random_engine::result_type seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
// Generate a random index into the string table:
std::uniform_int_distribution<size_t> distribution(0, n-1);
// A random number from distribution:
const size_t x = distribution(generator);
// Our random string:
const char* const s = insults[x];
cout << s << endl;
return EXIT_SUCCESS;
}

char uninitialized, isnumber method unidentified,

I'm having errors in my code below,
This is my code:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
two errors,
it says that identifier is unknown,
and
it says variable char is uninitialazed local variable,
change this while (Isnumber(ch)){ into do-while loop.
do{
.....
}while (Isnumber(ch))
The error is because ch is declared and it is used before initialized.
Also include #include <stdio.h>; for getchar();
Better do it in one loop:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
And before asking similar questions read this first (or buy a book).
Well I solved it using cin functions as below,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
I removed one while loop.
and used cin.fail and cin.good to avoid using IsNumber. And it worked.

Sorting alphabetically

Here is my code...What would be the best way to sort names alphabetically?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
string sname[25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++)
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++)
{
cout << sname[output] << endl;
}
system ("pause");
return 0;
}
The standard way is to use std::sort:
#include <algorithm>
// ...
std::sort(sname, sname + StudentNum);
std::sort uses operator< by default, which actually does an alphabetical comparison for strings.
EDIT: Indeed, it should be StudentNum instead of 25.