How to pass a local variable to another function? - c

So I am doing a text adventure game. It has Hundreds of lines of story, a fully functioning combat system, and I am now trying to create an influence system. Basically it is supposed to work like this: Certain responses/actions will increase or decrease your influence over different characters. I want to use the influence variable in choice_6() and story_7(). How do I do that? Please do not send me any links. I've gone through many many other answers and they haven't made sense to me so if your going to copy and paste, at least explain it a different way than other answers. Thank you.
int choice_6()
{
int influence = 0;
int choice = 0;
printf("What do you do?\n");
printf("\t1. You: No. I know absolutely nothing about you. You could be a monster\n");
printf("\ttoo for all I know! Normal people don't turn into frogs!\n");
printf("\t2. You: Your right we should keep moving. You can tell me when your\n");
printf("\tready.\n");
printf("\t3. You: Okay where do you think should we go then?\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\tBrie flashes a pained look on her face and you immediately regret saying that.\n");
printf("\tBrie: You really think I'm a monster?\n");
system("pause");
influence -= 10;
printf("You lose influence and are now at %i with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Your right we should keep moving.\n");
break;
}
case 2:
{
printf("\tBrie: Thank you. I'd rather not discuss this my life story in a dark\n");
printf("\tdungeon.\n");
system("pause");
influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: I'd have to agree with you there. Let's see what is up these stairs.\n");
choice = 2;
break;
}
case 3:
{
printf("Brie smiles at this.\n");
printf("\tBrie: Well the only way out seems to be these stairs so let's go up.\n");
system("pause");
influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their effectiveness in combat, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Sounds good to me I am quite frankly done with dungeons about now.\n");
break;
}
default:
{
printf("Type the number for the choice you want to do\n");
system("pause");
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
}
int story_7()
{
printf("\ninfluence is %i\n", influence);
printf("You lead the way walking upstairs\n");
system("pause");
printf("You turn the corner while crouched to find a room full of gremlins and goblins.\n");
system("pause");
printf("You grab Brie's hand and roll to the left behind some crates before they see you.\n");
system("pause");
printf("Even though you realize you will probably not make it out of this situation\n");
printf("alive, you can't help but feel lucky with Brie being so tightly pressed against you on the floor.\n");
system("pause");
printf("After a long period of silence to confirm nobody has seen you both enter,\n");
printf("Brie looks up at you and rolls her eyes.\n");
system("pause");
printf("*whispers*\tBrie: At least buy me dinner first jeez.\n");
system("pause");
printf("*whispers*\tYou: I'd love to but we should probably kill these uglies first.\n");
system("pause");
if (influence > 0)
{
printf("Brie laughs at this and slowly leans you off her to have both of you crouch.");
system("pause");
}
else
{
printf("Brie: Ugh just get off of me!\n");
printf("Brie pushes you off her violently and you manage to stay crouched.");
system("pause");
}
}
int main()
{
int play = 0;
int influence = 0;
intro_1();
story_1();
choice_1();
story_2();
choice_2();
story_3();
choice_3();
story_4();
choice_4();
story_5();
choice_5();
intro_2();
combat_1();
story_6();
choice_6();
story_7();
choice_7();
system("pause");
}

You can pass a pointer to the influence variable, if you want to modify it from within a function. Like this:
int choice_6(int *influence)
{
// ...
*influence -= 10;
// use *influence wherever you would have had used influence before
// ...
}
int story_7(int influence)
{
// ...
if (influence > 0) ...
// ...
}
int main()
{
int influence = 0;
// ...
choice_6(&influence);
story_7(influence);
// ...
}
This is passing a pointer to choice_6() because you need to modify influence from within that function. This is passing the value to story_7() because you do not need to modify the influence value there.

You should create game object(s) that stores the state of the game, in this case, influence and other event flags.
You will then need to either set this game object as a global, or pass it around by pointer/reference to every functions that may need to check or modify the game state.
struct MyGame {
int influence;
int has_cheese;
};
void choice_6(struct MyGame * game) {
...
game->influence += 10;
...
}
int main(...) {
struct MyGame game;
game->influence = 0;
game->has_cheese = FALSE; // or 0
...
choice_6(&game);
....
}

You need to pass the influence variable by reference. This means the function(s) you give the reference to can change the value of the variable itself (not just a copy of the variable).
Do this by prepending the parameter with a * in the function signatures, and passing with a & prepended:
int choice_6(int *influence)
{
....
int main()
{
int play = 0;
int influence = 0;
choice_6(&influence);
....

Related

What memory is my program trying to access? because its seg faulting

**I have traced through the code 3 times but I still cant figure out the cause of the seg fault, I am trying to get a menu printed by opening files and displaying the contents in organized form, it so frustrating, I am already confused by my code and even more so by seg fault, any help would be highly appreciated, I know this will turn into a code review
​
typedef struct{
char item[30];
char quantity[20];
int calories;
float protein;
float carbs;
float fats;
} food;
typedef struct {
char month[4];
int day, year;
} date;
int foodCount; // counter variable to keep track of the number of foods that are chosen
void initializeArray(FILE *dataFile, int arraySize, food foodType[]) // arrayProcessing.c
{
int i;
// struct food foodType[arraySize];
for(i=0;i<arraySize;i++)
{
scanf("%s",foodType[i].item);
scanf("%s",foodType[i].quantity);
scanf("%d",&foodType[i].calories);
scanf("%f",&foodType[i].protein);
scanf("%f",&foodType[i].carbs);
scanf("%f",&foodType[i].fats);
}
}
// used for the food arrays as well as the chosen foods
void printArray(int arraySize, food foodType[]) // arrayProcessing.c
{
int n;
printf("FOOD ITEM%25s%9s%10s%8s%8s\n","QUANTITY","CALS","PRO","CARBS","FAT");
for(n=0;n<arraySize;n++){
printf("%d. %-20s\t%10s\t%3d\t%5.2f\t%5.2f\t%5.2f\n",n+1,foodType[n].item,foodType[n].quantity,
foodType[n].calories, foodType[n].protein, foodType[n].carbs, foodType[n].fats);
}
}
int printMainMenu() // menu.c
{
int choice;
printf("\n MAIN MENU");
printf("\n 1. choose lean protein");
printf("\n 2. choose fruit");
printf("\n 3. choose complex carbs (starches & grains)");
printf("\n 4. choose fibrous carbs (veggies & greens)");
printf("\n 5. choose dairy");
printf("\n 6. choose fats, oils, nuts, seeds");
printf("\n 7. show totals");
printf("\n 8. quit program");
scanf("%d", &choice);
return choice;
int main (){
int arraySize, choice;
FILE *dataFile;
food foodType[arraySize];
do
{
choice=printMainMenu();
switch(choice)
{
case 1: {
dataFile=fopen("leanProteins.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile, arraySize, foodType);
printArray(arraySize, foodType);
break;
}
case 2:{
dataFile=fopen("fruit.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile,arraySize, foodType);
printArray(arraySize, foodType);
break;
}
case 3:{
dataFile=fopen("complexCarbs.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile,arraySize,foodType);
printArray(arraySize, foodType);
break;
}
case 4:{
dataFile=fopen("fibrousCarbs.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile,arraySize,foodType);
printArray(arraySize, foodType);
break;
}
case 5:{
dataFile=fopen("dairy.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile, arraySize, foodType);
printArray(arraySize,foodType);
break;
}
case 6:{
dataFile=fopen("fats.txt","r");
fscanf(dataFile,"%d",&arraySize);
initializeArray(dataFile, arraySize, foodType);
printArray(arraySize,foodType);
break;
}
case 7:{
printf("show totals");
break;
}
case 8:{
exit(0);
}
default:
printf("invalid selection!");
}
}while(choice!=8);
return 0;
}
Hint only since this is almost certainly classwork, and you'll become a much better developer if you learn to nut things out yourself :-)
int arraySize, choice;
FILE *dataFile;
food foodType[arraySize];
Here's a question you should ask with regard to the snippet above. What is the value of arraySize at the point where the foodType array is created?
A couple of other things to consider.
You're likely going to run out of file handles if you keep opening files and not closing them.
You appear to want to read food details from a file (which you open) but you never actually use the file handle. Instead, you scanf the information from standard input.
And, on that scanf (specifically with "%s"), you need to be absolutely certain that your data is correct. Crashing is frequently caused by reading in a string that's too long for the buffer you've provided.
Still with the scanf("%s"), you should be aware that it will stop on the first whitspace so, if your file contains the "Long grain Basmati" complex carb, all you're going to see is Long. And this will almost certainly complicate your input as you try to read the rest of the line as non-string data (like a calorie count of "rice", for example).
You should generally always check the return value of the scanf family to ensure it has scanned the number of items you expected.
Those last three points could probably be solved with a more robust input function, one which prevents buffer overflow and checks the data being read to ensure it's valid (like reading as a string first, checking the content as a string, then converting to integer or float).
I have such a beast here that works well for standard input, it reads the entire line safely. It wouldn't be hard to adapt this to use any file handle and then you could use sscanf to turn that into individual fields after checking.

Using "If Statements" in basic C programming. How can I properly format them?

To begin, the code that I have got up to this point is below.
The calculator does everything I want it to, minus the fact that it still includes negative numbers in its calculations. I would like for it to do nothing if the number presented as the radius is less than zero, yet still calculate if the number is non-negative. However, I am having issues with using an if statement. I have not used these before, as I am really just a beginner. I just need a push in the right direction. Do I need to have an "else"? Any help is greatly appreciated!
#include <stdio.h>
int radius, area;
main()
{
printf("Enter radius: ");
scanf("%d", &radius);
{
if (&radius > -1); {
area = (int)(3.14159 * radius * radius);
printf("Area = %d\n", area);}
else {
return(0); }
}
return(0);
}
Remove semi-colon
remove semi-colon this lines
if (&radius > -1); {
should be
if (radius > -1) {
Should do this for easier tracking if-else statement
change these lines
printf("Area = %d\n", area);}
return(0); }
to
printf("Area = %d\n", area);
}
return(0);
}
Here is style for if-else statement, I think it's easier for you to track your code
if (condition) {
statements;
}
else if (condition) {
statements;
}
else {
statements;
}
The C compiler doesn't care about formatting, in theory you can do whatever you like, and there's no consensus for what is/isn't "proper formatting".
However, most programmers stick to a specific style so that it's easier to read the source code; and if you're working in a team then it's nice if all programmers on the team use the same style so that all of the source code is consistent. To achieve that, there may be a formal "style guide", and if there is you should follow it.
Beyond that, there are some common rules that almost everyone follows:
nested blocks that are delimited by braces are indented somehow (with either "N space characters" or "N tab characters") relative to the parent block
cases of a switch statements will be exceptions to the indentation rules. Typically each case's statements are indented even though there's no braces; and the case keyword itself may or may not be indented by the parent switch's braces.
either all braces are always on a line by themselves; or starting braces are at the end of the line and ending braces may be at the start of a line containing a related statement
when a block consists of a single statement; either it always uses braces and is takes up a line by itself, or it never uses braces and shares the same line as its parent.
the else if pair is always an exception to the "block consists of a single statement" rule (the if is a single statement that is never treated as a separate block, and people pretend else if is a single elseif keyword).
What this means is that (depending on who got their way when arguing about it) this might acceptable:
int main() {
int area;
printf("Enter radius: ");
scanf("%d", &radius);
switch(radius) {
case 0:
return 0;
case 1:
return 1;
}
if (&radius > -1) {
area = (int)(3.14159 * radius * radius);
printf("Area = %d\n", area);
} else return -1;
return area;
}
..and this might also be acceptable:
int main()
{
int area;
printf("Enter radius: ");
scanf("%d", &radius);
switch(radius)
{
case 0:
return 0;
case 1:
return 1;
}
if (&radius > -1)
{
area = (int)(3.14159 * radius * radius);
printf("Area = %d\n", area);
}
else
{
return -1;
}
return area;
}
if (&radius > -1);
Lose the & before radius and lose the semicolon:
if ( radius > -1 ) { ... }
Do I need to have an "else"?
In this particular case, no. You're not doing anything in the else branch that you aren't already doing unconditionally (i.e., the return statement). You'd only need an else branch if you needed to take a specific action only when the condition fails, such as printing an error message:
if ( radius > -1 )
{
...
}
else
{
printf( "Radius needs to be non-negative!\n" );
}
return 0;
As for how to format, there are multiple styles with their own advantages and disadvantages. The style I prefer has the { and } on their own lines:
if ( condition )
{
// if branch
}
else if ( another condition )
{
// else if branch
}
else
{
// else branch
}
This style is easiest for me to read, makes it clearer where blocks begin or end, etc. It also increases the use of vertical space, so you get less code in a window, meaning you may have to scroll back and forth a bit more.
There's what's known as the K&R style as it was popularized by Kernighan & Ritchie, where the opening { is on the same line as the if or else:
if ( condition ) {
// if branch
}
else if ( condition ) {
// else if branch
}
else {
// else branch
}
Not quite as easy to pick out where a block starts, but not too bad, and somewhat more compact, so you can fit more lines of code into a limited space.
Then there's a style I flat-out hate, which puts the closing } on the same line as the else or else if:
if ( condition ) {
// if branch
} else if ( condition ) {
// else if branch
} else {
// else branch
}
I find this style very hard to read and follow. But, it's the most compact style, and commonly used in situations where screen real estate is very limited (such as in a PowerPoint slide in a lecture or tutorial or something).
Note that the compiler doesn't care which style you use, as long as the opening and closing braces match up properly. You could put everything on a single line with almost no whitespace like:
if(radius>-1){area=(int)(3.14159*radius*radius);printf("Area = %d\n", area);}else{print("Radius needs to be non-negative!\n");}
Formatting only matters for you and anyone who has to read/maintain your code. Whatever style you pick, be consistent with it.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

In C, How can I evaluate a local variable thats in one function, in a different function?

Ok so I'm creating this text adventure game. To be all unique and different, I decided to add an influence system where your responses to other characters can affect their responses to you as well their combat effectiveness.
I have a fair amount of experience in C++ and I just started my second semester-long course in C. So far, I have tried using global variables, structs, static variables, and using functions inside of other functions. I also tried using pointers but I kept getting errors every time so I stopped. This is a snippet of code that tries to use the influence system(Sorry for the stars, wouldn't want to give away any story plots):
#include <stdlib.h>
#include <stdio.h>
static int positive_Influence; int negative_Influence; int overall_Influence;
void printpInI(int positive_Influence, int negative_Influence);//positive and negative influence
int choice_6()
{
int choice = 0;
int positive_Influence, negative_Influence, overall_Influence;
positive_Influence = 0;
negative_Influence = 0;
overall_Influence = 0;
printf("What do you do?\n");
printf("\t1. You: ****\n");
printf("\t2. You: ****\n");
printf("\t3. You: ****\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\t****?\n");
system("pause");
negative_Influence += 10;
printf("You lose influence and are now at %i with ****.\n", positive_Influence-negative_Influence);
break;
}
case 2:
{
printf("\t****");
system("pause");
positive_Influence += 10;
printf("You gain influence and are now at %i influence with ****.\n", positive_Influence-negative_Influence);
break;
}
case 3:
{
printf("**** smiles at this.\n");
system("pause");
positive_Influence += 10;
printf("You gain influence and are now at %i influence with ****.\n", positive_Influence-negative_Influence);
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
overall_Influence = positive_Influence-negative_Influence;
printf("%i\n", overall_Influence);
}
void story_7()
{
printf("Your overall influence is %i\n", overall_Influence);
}
int main()
{
choice_6();
story_7();
system("pause");
}
You have declared overall_influence as a global but also as a local in choice_6. The local declaration takes precedence; just remove that and you should be OK. Same thing about the variables positive_influence and negative_influence.
Can you tell me which type of errors you got? Also you already declared global variables for calculating influence so why you again declared it locally in choice_6 function and that is the error case in you program so local variables have more precedence then global one within function in which they declared. So remove declaration from function choice_6.
I actually was just being really dumb because I forgot hows pointers worked (dam ampersans!) anyway thank you all for replying I really really do appreciate it. I am also working on a combat system that can use multiple enemies so keep watching my profile because I'll probably have moar questions later. If you would like to beta test, my email is mikemanahan15#gmail.com if you would like to play what I have so far. Of course, here is the finished code (for choice_6 and story_7) enjoy:
#include <stdlib.h>
#include <stdio.h>
int choice_6(int *influence)
{
int choice = 0;
printf("What do you do?\n");
printf("\t1. You: No. I know absolutely nothing about you. You could be a monster\n");
printf("\ttoo for all I know! Normal people don't turn into frogs!\n");
printf("\t2. You: Your right we should keep moving. You can tell me when your\n");
printf("\tready.\n");
printf("\t3. You: Okay where do you think should we go then?\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\tBrie flashes a pained look on her face and you immediately regret saying that.\n");
printf("\tBrie: You really think I'm a monster?\n");
system("pause");
*influence -= 10;
printf("You lose influence and are now at %i with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Your right we should keep moving.\n");
break;
}
case 2:
{
printf("\tBrie: Thank you. I'd rather not discuss this my life story in a dark\n");
printf("\tdungeon.\n");
system("pause");
*influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: I'd have to agree with you there. Let's see what is up these stairs.\n");
choice = 2;
break;
}
case 3:
{
printf("Brie smiles at this.\n");
printf("\tBrie: Well the only way out seems to be these stairs so let's go up.\n");
system("pause");
*influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their effectiveness in combat, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Sounds good to me I am quite frankly done with dungeons about now.\n");
break;
}
default:
{
printf("Type the number for the choice you want to do\n");
system("pause");
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
}
int story_7(int influence)
{
if (influence > 0)
{
printf("Brie laughs at this and slowly leans you off her to have both of you crouch.");
system("pause");
}
else
{
printf("Brie: Ugh just get off of me!\n");
printf("Brie pushes you off her violently and you manage to stay crouched.");
system("pause");
}
}
int main()
{
int influence = 0;
// ...
choice_6(&influence);
story_7(influence);
// ...
}
You should remove the local variables and use scope resolution operator to use your global variables
This would solve your question.
Also you can use these variables in any function you want later.

program running through my if else after function call

I have a class assignment in C to make a simple calculator that performs three calculations. I haven't completed all of the functions yet but I am having a problem with my calcMenu function. When the function is called the program runs through all of the if else statements and unknown to me, performs only the else statement which is error checking. Than the function is run again which is intended but this time it does not run through all of the if else statements and allows the user to make a choice. I know I have done something really stupid but have been racking my brain for the last hour. If anyone has any pitty for me, than please point me in the right direction. I know all the system calls will Irk some but this is a basic class and our instructor has told us to use them.
Thanks in advance,
Mike
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")
//Prototype calculate functions here
void evenOrOdd(int userNumber);
void squareNum(int userNumber);
void cubeNum(int userNumber);
void calcMenu(int userNumber);
void main() {
//Declare local variables here
int userNumber = 0;
printf("\t\t\tThe amazing three function caluculator\n\n\n");
printf("Please enter a whole number that you would like to calculate\n");
scanf("%d", &userNumber);
calcMenu(userNumber);
}
void calcMenu(int userNumber)
{
char calculateOption;
printf("\nWhat calculation would you like to perform with your number?\n\n");
printf("Press A.) to check if your number is even or odd.\n\n");
printf("Press B.) to calculate the square of your number.\n\n");
printf("Press C.) to calculate the cube of your number.\n\n");
printf("press D.) to exit the program.\n");
scanf("%c", &calculateOption);
calculateOption = toupper (calculateOption);
if (calculateOption == 'A')
{
evenOrOdd(userNumber);
}
else if (calculateOption == 'B')
{
squareNum(userNumber);
}
else if (calculateOption == 'C')
{
cubeNum(userNumber);
}
else if (calculateOption == 'D')
{
system("cls");
printf("Thank You for using my amazing calculator.\n\n");
system ("pause");
system ("exit");
}
else
{
printf("Please enter a valid choice");
calcMenu(userNumber);
}
}
void evenOrOdd(int userNumber) {
userNumber = userNumber %2;
if (userNumber == 0)
{
printf("Your number is even. \n");
}
else
{
printf("Your number is odd. \n");
}
}
void squareNum(int userNumber) {
}
void cubeNum(int userNumber){
}
When you read input with scanf you have to press the Enter key to make the program continue. Your scanf call reads the single character from the input, but leaves the Enter key still in the input buffer, to be read next time you call scanf.
There is a very simple trick to solve that: Place a space in the scanf format string before or after the "%c". This will make scanf skip whitespace.
scanf("%c ", &calculateOption);
If you stepped through the code with a debugger you would have easily seen that calculateOption would have been the newline character.
First of all, You can condense all those printf statements into one function to save the extra calls.
Next, you should probably indent your functions, I can't tell where one begins and another ends at a glance.
Third, don't use system("pause"), use getchar().
Fourth, this is optional, you might want to turn those if statements into a switch statement.
Now, on to your question. First of all, instead of using scanf("%c", &calculateOption), just use getchar() here too. In this case, I would write calcMenu() as this:
int calcMenu(int userNumber){
printf("\nWhat calculation would you like to perform with your number?\n\n\
Press A.) to check if your number is even or odd.\n\n\
Press B.) to calculate the square of your number.\n\n\
Press C.) to calculate the cube of your number.\n\n\
Press D.) to exit the program.\n");
switch(toupper(getchar())){
case 'A':
evenOrOdd(userNumber);
break;
case 'B':
squareNum(userNumber);
break;
case 'C':
cubeNum(userNumber);
break;
case 'D':
system("cls"); //this is bad, really.
printf("Thank You for using my amazing calculator.\n\n");
getchar();
return 0;
default:
printf("Please enter a valid choice: ");
calcMenu(userNumber);
break;
}
}
Also, main should always return a value. void main is bad practice.
Disclaimer: The code isn't tested, you shouldn't copy/paste it anyways. I also don't know if you're being forced to use some things or not...

Resources