My program isnt working after the scanf statement - c++

My code isn't working after the second scanf statement. I'm still new to C++ so im not sure what I am doing wrong. I've looked on this website as well as others and so far havent found anything. I've also tried the fflush statement but that didnt fix it either, any other suggestions would be great thanks.
include <stdio.h>
int main(void)
{
//Intro message
printf("This program will take the order of a customer and then subtract their order from the inventory list. After calculations a new inventory list will appear\n");
// declare variables
int dough, sauce, cheese, pepperoni, sausage, greenPeppers, blackOlives, mushrooms;
int num1;
char pizza;
// create inventory
dough = 50;
sauce = 50;
cheese = 50;
pepperoni = 50;
sausage = 50;
greenPeppers = 50;
blackOlives = 50;
mushrooms = 50;
//display the inventory
printf("\n The currrent inventory is: \n Dough:%d", dough);
printf("\n Sause:%d", sauce);
printf("\n Cheese:%d", cheese);
printf("\n Pepperoni:%d", pepperoni);
printf("\n Sausage:%d", sausage);
printf("\n Green Peppers:%d", greenPeppers);
printf("\n Black Olives%d", blackOlives);
printf("\n Mushrooms:%d", mushrooms);
//get customer input
printf("\nWhat type of pizza would you like? Please type a lowercase letter and only chose one. Type C for Cheese, P for Pepperoni, S for Sausage, and V for Veggie.\n");
scanf_s(" %c", &pizza);
printf("\nHow many pizzas would you like to order? Maximum of 10.\n");
scanf_s(" %d", &num1);
//This is where it stops
printf("It cuts out here, why can I not see anything after this line?");
// calculate what inventory will be taken out
cheese = cheese - num1;
dough = dough - num1;
sauce = sauce - num1;
switch (pizza)
{
case 'c':
cheese = 50 - num1;
break;
case 'p':
pepperoni = pepperoni - num1;
break;
case 's':
sausage = sausage - num1;
break;
case 'v':
blackOlives = blackOlives - num1;
greenPeppers = greenPeppers - num1;
mushrooms = mushrooms - num1;
break;
}
// display final inventory
printf("The new inventory is: \n Dough:%d", dough);
printf("\n Sause:%d", sauce);
printf("\n Cheese:%d", cheese);
printf("\n Pepperoni:%d", pepperoni);
printf("\n Sausage:%d", sausage);
printf("\n Green Peppers:%d", greenPeppers);
printf("\n Black Olives%d", blackOlives);
printf("\n Mushrooms:%d", mushrooms);
return 0;
}

The problem is that you are using scanf (or its cousin scanf_s). The scanf problem is not suitable for interactive input, and leads to confusing results like what you're seeing.
Instead, use the fgets function to read data into a character array. If you need to convert that character array into a number, use atoi.

Related

Why does the console asks for more inputs? C++

I am trying to make a program where I calculate fees based on the ride type and time the user rented stuff. I came up with the method of how to do it, but when I try to read input the console keeps asking for more input.
double computeFee(){
double fee, hour_rate, minute_rate;
char ride_type, colon;
int hour_started, minute_started, hour_ended, minute_ended, total_minutes;
cin >> ride_type >> hour_started >> colon >> minute_started >> colon >> hour_ended >> colon >> minute_ended;
total_minutes = ((hour_ended * 60) + minute_ended) - ((hour_started * 60) + minute_started);
switch(ride_type){
case 'J':
hour_rate = 500;
minute_rate = 10;
break;
case 'K':
hour_rate = 200;
minute_rate = 5;
break;
case 'B':
hour_rate = 100;
minute_rate = 2;
break;
case '0':
return 1;
break;
}
if (total_minutes < 60){
fee = total_minutes * minute_rate;
}else{
fee = ((total_minutes/60) * hour_rate) + ((total_minutes%60) * minute_rate);
}
return fee;
}
int main(){
double total, fee;
computeFee();
fee = computeFee();
cout << fee;
return 0;
}
Each time you call computeFee(), the function code is executed. In your code, you call it twice, so it will ask you for the input two times. And given that the first time you call it you don't assign it, the first input will be lost.
To make it work the way you want, your main code should be:
int main(){
double fee;
fee = computeFee();
cout << fee;
return 0;
}

Function automatically looping?

Ok, so this function is supposed to take results from a user and then give them an option to input more results or return to the main menu main() when they're done.
Everything works fine. the only problem is at the last scanf statement before the switch.
Instead of waiting for the users input in userChoice, its automatically starting the function over again. Its only supposed to do that if userChoice is 'a' or 'A' but it just completely ignores the scanf statement and the switch as well, it seems. What am i doing wrong? Scroll down to see the line im referring to.
void inputResults(int gameNumber, int i, int j)
{
int Results[ROWS][COLS];
char userChoice = ' ';
if (j >= COLS)
{
j = 0;
i = i + 1;
}
if (gameNumber > ROWS)
{
printf("\nJk, Max number of games reached\n");
main();
}
gameNumber = gameNumber + 1;
printf("\nHow many points did the home team score in game %d?\n", gameNumber);
scanf_s("%d", &Results[i][j]);
j = j + 1;
printf("\nHow many points did the opponents score in game %d?\n", gameNumber);
scanf_s("%d", &Results[i][j]);
printf("\nHome: %d Opponents: %d\n", Results[i][j-1], Results[i][j]);
printf("\nA) Enter results for game %d\nB) Main menu \n", (gameNumber + 1));
*************************PROBLEM***********************************
scanf_s("%c", &userChoice); /*it ignores THIS it just loops the
function after it prints the above*/
switch (userChoice) //it doesnt even get to this.
{
case 'A':
inputResults(gameNumber, i, j);
case 'a':
inputResults(gameNumber, i, j);
case 'b':
main();
case 'B':
main();
default:
printf("\nThats still not a valid choice dude\n");
}
}
the values passed into gameNumber, i, and j are all all 0 if you're wondering. They were passed from the main function
When you read a single character with scanf_s like
char ch;
scanf_s("%c", &ch, 1);
and enter for eg. the letter 'A' and press enter, the 'A' ends up in ch but the '\n' from you pressing enter remains in stdin. On the next call to scanf_s() this '\n' is read and stored in ch without giving you the chance of making any input.
Use
scanf_s("%c[^\n]", &ch, 1);
instead which will read and discard all extra characters still in stdin up to the next newline character.

C++ read number string and capture specific position character as int

I need my program to read a string of numbers input by the user and then assign each number to an int variable:
94715 is input by the user as string
then
a=9
b=4
c=7
d=1
e=5
so I can
if (a < b), c*d+e, a-e, etc
I've searched some commands (getline, string.substr(ind,n), getc, fgetc, atoi, etc) I know I'm close but I can't find examples of exactly what I'm looking for.
The simplest and most direct way I've found is
stringstream convert(string1);
convert>>variable;
but it converts the whole string, if there was a way to add an ind position in it like
string1.substr(0,1)
that'd do the trick...
It is as simple as this:
std::string num = "94715";
size_t i = 0;
assert( num.length() > 4 );
int a = num[i++] - '0';
int b = num[i++] - '0';
int c = num[i++] - '0';
int d = num[i++] - '0';
int e = num[i++] - '0';
note: this may not work properly on systems not using ACII encoding, but it is unlikely you would hit such problem.
int number = 9544;
int vector[10]; // you can make it as big as you want or simply use std::vector
int position = 0;
while (number != 0)
{
vector[position++] = number % 10; // this assigns the last digit
number = number / 10; // remove the last digit
}
for(int i=0; i<position; i++)
std::cout << vector[i]; // this will print 4459
Now you have your number's digits inside an int vector.
This example uses chars because a string is still a char array.
This is for if you are on Windows. Just input and press the enter key.
Like Dieter Lücking suggested, it does this character by character.
It uses kbhit() and getch() found in conio.h to process single characters.
Then it multiplys the characters with appropiate position to get full integer.
And then it stores them in the array digitArray[ ], and assigns them to a,b,c,d or e after. Now you can do whatever with a,b,c,d and e.
Here is some code to demonstrate.
// Re: Now it is just clunky
// one ten hundred thousand
// 1 2 3 4
//digitn=digitArray[3]*1 + digitArray[2]*10 +digitArray[1]*100 +digitArray[0]*1000
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int digit=0,digitInput=0;
int digitArray[10]={0},digitn;
int numberOfInputDigits=7;
void SplitIntoDigits(void);
int a=0,b=0,c=0,d=0,e=0,f=0;
int main(){
system("color 1F"); //Blue background
while(1){
cout<<"\nPlease enter number. Max Input is "<<numberOfInputDigits<<" individual digits \n";
cout<<"or press enter when done \n>" ;
memset(digitArray,0,sizeof(digitArray));
a=0;b=0;c=0;d=0;e=0;f=0;
SplitIntoDigits();
//cout<<"\n"<<digitArray[7]="<<digitArray[7];
cout<<"\n\n";
a = digitArray[0];
b = digitArray[1];
c = digitArray[2];
d = digitArray[3];
e = digitArray[4];
f = digitArray[5];
cout<<"a = "<< a <<"\n";
cout<<"b = "<< b <<"\n";
cout<<"c = "<< c <<"\n";
cout<<"d = "<< d <<"\n";
cout<<"e = "<< e <<"\n";
cout<<"f = "<< f <<"\n";
cout<<"\n\n The whole combined int number is "<<digitn<<"\n\n";
}
return 0;
}
/*********************************
* *
********************************/
void SplitIntoDigits(void){
digitArray[0]=0;
digitArray[1]=0;
digit=0;
digitInput=0;
while((digit<numberOfInputDigits)){
if (kbhit()){
digitInput=getch();
if (digitInput==27) exit(0);
if ((digitInput>47) && (digitInput<59)) {
digitArray[digit]=(unsigned char)digitInput-48;
digit++;
cout<<digitInput-48;
}
if (digitInput==13) { digitn=digitArray[0]; break; }
}
}
switch(digit) {
case 0:
case 1:
digitn=digitArray[0]*1 ;
break;
case 2:
digitn= digitArray[1]*1 +digitArray[0]*10 ;
break;
case 3:
digitn= digitArray[2]*1+digitArray[1]*10 +digitArray[0]*100 ;
break;
case 4:
digitn=digitArray[3]*1+digitArray[2]*10+digitArray[1]*100+digitArray[0]*1000 ;
break;
case 5:
digitn=digitArray[4]*1+digitArray[3]*10+digitArray[2]*100+digitArray[1]*1000+digitArray[0]*10000 ;
break;
case 6:
digitn=digitArray[5]*1+digitArray[4]*10+digitArray[3]*100+digitArray[2]*1000+digitArray[1]*10000
+digitArray[0]*100000;
break;
case 7:
digitn=digitArray[6]*1+digitArray[5]*10+digitArray[4]*100+digitArray[3]*1000+digitArray[2]*10000
+digitArray[1]*100000 +digitArray[0]*1000000;
break;
case 8:
digitn=digitArray[7]*1+digitArray[6]*10+digitArray[5]*100+digitArray[4]*1000+digitArray[3]*10000
+digitArray[2]*100000 +digitArray[1]*1000000+digitArray[0]*10000000;
break;
case 9:
digitn=digitArray[8]*1+digitArray[7]*10+digitArray[6]*100+digitArray[5]*1000+digitArray[4]*10000
+digitArray[3]*100000 +digitArray[2]*1000000+digitArray[1]*10000000 +digitArray[0]*100000000;
break;
}
// if (digitInput!=13) digitn=digitArray[3]*1+digitArray[2]*10+digitArray[1]*100+digitArray[0]*1000 ;
//cout<<("\n%i\n\n",digitn);
}
/*********************************
* *
********************************/

Basic C++ Dice game

I have a problem here, would be really nice if anyone could help me out here. Its my first time using this program so dont be to judgemental.
#include <cstdlib>
#include <iostream>
using namespace std;
int throw1, throw2, throw3, throw4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3);
int deposit;
int account;
int main(){
int count = 0;
while(count < 3){
cin>>deposit;
while(deposit>5000 || deposit<0){ //Makes sure so that my deposit is between 0-5000
cout<<"deposit failed"<<endl;
cin>>deposit;
}
account = deposit;
cout<<"You have deposited" <<deposit<<"Swedish Krona"<<endl;
cout<<"and you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
if (konto>499){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet2=300, bet3=500"<<endl;
cin>>bet1;
cin>>bet2;
cin>>bet3;
account = (deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>299){
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet=300"<<endl;
cin>>bet1;
cin>>bet2;
account =(deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>99){
cout<<"please place your bet"<<endl;
cout<<"bet1=100"<<endl;
cin>>bet1;
cout<<"you have placed your bet"<<bet<<"Swedish Krona"<<endl;
}
while (account<100 || deposit>5000){
cout<<"insufficient funds"<<endl;
cin>>deposit;
account=deposit;
}
{
cout<<"Throw dice"<<endl;
srand(time(0));
Throw1 = rand() % 6 + 1;
Throw2 = rand() % 6 + 1;
Throw3 = rand() % 6 + 1;
Throw4 = rand() % 6 + 1;
cout<<"You rolled"<<Throw1<<endl;
cout<<"You rolled"<<Throw2<<endl;
cout<<"Computer rolled"<<Throw3<<endl;
cout<<"Computer rolled"<<Throw4<<endl;
}
}
count++;
system ("pause");
}
So the thing here is that, for some reason i always bet 500, even though type in bet1 or bet2, and i have no clue how to fix that problem. And then my loop function (int count 0; while(count < 3)count++) it starts to loop endlessly without me pressing anything, even though i use the same loop function in simple coding like just typing some cout<< things it works fine, but when i use it in this code, it goes to drain, do anyone know why this is happening, would appreciate if anyone could answer, thanks in advanced.
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3)
The last line will be evaluated like this: 100, 300, 500. Result of comma separated list of expression will be last value, which is 500. So your bet variable will be always set to 500.
What you state in your comment below the code, (int count 0; while(count < 3)count++)looks like some weird mixture of for and while loop. Please check again your C++ textbook/online tutorials about how to write a correct loop.
In the code you show, in your while loop, you don't modify the count variable - therefore it will loop forever if count is < 3 before the loop. The indentation of your code is really misleading. I have taken the liberty of reformatting your code - and now you should see that the count++ statement actually is outside of your main while loop!
When you want to do something for a fixed number of times, it's recommendable to use a for loop, it makes it harder to forget the increment!
You increase count outside the loop, so it will always be zero. Either move it inside the loop (proper indentation is key!) or maybe use a for loop instead:
for (count = 0; count < 3; ++count) { ... }
Some advice,
place your prompt for deposit (insattning) into a function
place your prompt for bet into a function
check for sufficient money before prompting for bet
get input into a string, then validate input (not done below, yet)
check that bet is valid (=100,=300,=500, bet<=konto)
Here are these convenience functions,
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
int kast1, kast2, kast3, kast4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=0; //assignment didn't make sense
int insattning=0;
int konto=0;
//deposit
int get_insattning()
{
int good = 0;
while( !good )
{
cout<<"deposit"<<endl; //prompt for deposit
cin>>insattning;
if(insattning>5000 || insattning<0)//Makes sure so that my deposit is between 0-5000
{
cout<<"insattning fel, var vänlig och gör rätt denna gången"<<endl;
}
else good = 1;
}
cout<<"du har nu satt in" <<insattning<<"kr"<<endl;
return insattning;
}
It isn't clear to me whether you want 1 bet of 100,300,or 500, or 3 bets. This does the first,
//bet
int get_bet()
{
int good = 0;
int bet;
std::string validbets = "";
if(konto<100){ cout<<"you need more money"; return 0; }
while( !good )
{
cout<<"var vänlig och placera ditt bet"<<endl;
if(konto>=100){ validbets = "bet1=100"; }
if(konto>=300){ validbets += ", bet=300"; }
if(konto>=500){ validbets += ", bet=500"; }
cout<<validbets<<endl;
cin>>bet;
if( bet >= konto ) {
cout<<"you don't have enough money"<<endl;
continue;
}
if (bet==500){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"du har så här mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==300){
cout<<"du har så mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==100){
cout<<"du har nu bettat "<<bet<<" kr"<<endl;
good = 1;
}
else {
cout<<"you must place valid bet"<<endl;
continue;
}
}
return bet;
}
Now your main game play is cleaner/easier to read. I don't know what the win conditions are or the payout, and since your prompts are not english, I cannot read them to tell what to do next,
int main()
{
int count = 0;
int bet;
srand(time(0));
for( count=0; (count < 3); count++)
{
konto = get_insattning();
if (konto<100)
{
cout<<"du har inte nog med pengar, vänligen sätt in pengar"<<endl;
continue;
}
cout<<"och du har så här mycket i ditt konto "<<konto<<" kr"<<endl;
bet = get_bet();
//when you bet, reduce konto by bet
konto = (konto - bet);
{
cout<<"slå tärningar"<<endl;
kast1 = rand() % 6 + 1;
kast2 = rand() % 6 + 1;
kast3 = rand() % 6 + 1;
kast4 = rand() % 6 + 1;
cout<<"Du fick"<<kast1<<endl;
cout<<"du fick"<<kast2<<endl;
cout<<"datorn fick"<<kast3<<endl;
cout<<"datorn fick"<<kast4<<endl;
}
You need to write code for determining whether you won or lost, and then add to konto when you win,
//did you win or lose?
//win? add money to konto
//lose? you have already deducted from konto
}
system ("pause");
}
These suggestions should help you fix your program.

Using switch case

This is what I have so far. It won't work. I'm trying to write it to get user input of an amount and the county they live in and the program outputs the total with taxes
#include<iostream>
using namespace std;
int main()
{
char amt = 0;
double county ;
char x = 0;
double total = 0;
total = amt + x;
x = county;
printf("\nplease enter amount\n");
scanf_s("%d",&amt);
printf("\nplease enter county\n");
scanf_s("%c",&x);
scanf_s("%c",&total );
printf("total:", amt * x);
switch(x)
{
case 'o':
printf("orange:",county = 0.06);
break;
case 'l':
printf("lake:",county = 0.07);
break;
case 's':
printf("seminole:",county = 0.08);
break;
}
system("pause");
}
When you use printf(), also specify which variables you are sending, so if you want to print a value use something like: printf("Value: %f\n", 0.07);.
You can find the format specifiers here.
You should put the switch clause before the line where you print the total. Also, from what I'm seeing you shouldn't multiply the amt * x but something like subtotal * (1 + county)
If scanf_s() is anything like scanf(), you should consider using the right conversions for the arguments ("%d" means 'int' and so on).