Can't get the if statements/while loop to work. If I make raceChosen an int it will never allow me to enter choose another race. When I use a char the if statements don't work. I have absolutely no idea who to fix this. Any assistance that could be provided would be appreciated.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
struct player { /*a struct to hold the player information.*/
int type[7];
int name[12];
int Smartness[7];
int Strength[7];
int MagicSkills[7];
int Luck[7];
int Dexterity[7];
int lifePoints[3];
}player;
int main(void)
{
struct player* ptr;
srand(time(NULL));
int numberPlayers,i,j,Smartness,Luck,Strength,Dexterity;
int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
lifePoints = 100;
char raceChosen[1];
printf("Please enter the number of players you would like");
scanf("%d",&numberPlayers); /*take in the number of players*/
struct player plyr[numberPlayers];
i = 0;
while( i<numberPlayers )
{
printf("Please enter the race you would like to play as \n"
"Press elf for Elf \n"
"Press 1 for Human \n" /*taking in the race from the user*/
"Press 2 for Ogre \n"
"Press 3 for Wizard \n");
scanf(" %c",&raceChosen);
if(raceChosen == "0"){
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength); /* generating the character */
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
if(raceChosen == "1"){
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength);
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
}
i++;
}
}
First of all, I would recommend you try to compile your code before asking questions.
Anyways, let's go through your compile errors step by step:
Line 43: Passing the wrong variable type to scanf
You only need one character from standard input, so no need for a string array (char *), just use a character variable (char)
So char raceChosen[1] becomes char raceChosen
Lines 46 and 69: Comparing two strings with == operator
This is a good reason to start learning the basics of C programming. To compare two strings in C, you use strcmp(first_string, second_string).
Since raceChosen is not a character array anymore, we don't need strcmp, we can still use == but the quotes around 0 and 1 have to be single quotes.
So your if statements become if(raceChosen == '0') and if(raceChosen == '1'). This is how you compare two characters.
Lines 23, 24 and 32, Lots of unused variables
I hope you're gonna use those later because this is bad practice.
Line 48: Using an uninitialized variable
Just initialize ptr to NULL (ptr = NULL) right after you declare it.
Just a notice tho, you don't need to use a pointer to struct here, unless you were asked to. A simple struct would do the work.
Line 98: Extraneous closing brace
Yup, just as it says, too many closing braces.
Change like this, i hope it work for you.
int main(void)
{
struct player* ptr;
srand(time(NULL));
int i,j,Smartness,Luck,Strength,Dexterity;
int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
lifePoints = 100;
char raceChosen[1];
static int numberPlayers=0; //Changed
printf("Please enter the number of players you would like");
scanf("%d",&numberPlayers); /*take in the number of players*/
struct player plyr[numberPlayers];
i = 0;
while( i<numberPlayers )
{
printf("Please enter the race you would like to play as \n"
"Press elf for Elf \n"
"Press 1 for Human \n" /*taking in the race from the user*/
"Press 2 for Ogre \n"
"Press 3 for Wizard \n");
scanf("%c",&raceChosen);
if(*raceChosen == '0'){ //Changed
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength); /* generating the character */
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
if(*raceChosen == '1'){ //Changed
printf("Please enter your name 1\n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength);
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
}
i++;
}
There are 2 major things to be considered within your code, lets correct them one by one:
char raceChosen[1]; <=> Here you have declared a charecter array of size 1
Please note : Array is collection of data of same type, so when you want to store at least 2 or more data, you could had used array, but here you are using a single charecter variable so you should avoid using array.
correct way: char raceChosen;
Secondly,
scanf(" %c",&raceChosen);
if (raceChosen == "0")
Here you are taking input racechosen as a charecter : "%c" is for charecter input, and while comapring you are comapring it with string : " "double quote is for string. ie; You are comapring
if (raceChosen == "0")
(char) (string)
This condition is not going to be true, hence you are not entering these if blocks.
correct way:
if (raceChosen == '0')
char char
Related
I am writing a calculator in C, but it will take input like 1+2*9/5.
I am not an expert in C, so I thought I can ask the user how many numbers he has (for example let's say 4), then asking 3 times "enter the number, enter operator" and 1-time "enter number". Then putting all inputs to an empty array respectively then doing the operations by looping through the array. But of course, I've got problems.
#include <stdio.h>
int main(void) {
int how_many;
printf("How many numbers do you have to calculate?");
scanf("%d", &how_many);
int number_entry = how_many; // for example 1+2*9/5 has 4 numbers
int operator_entry = how_many - 1; // and 3 operators
int number_in;
char operator_in;
int all_inputs[(number_entry + operator_entry)];
for (int j = 0; j < operator_entry; j++) {
printf("Enter the number : ");
scanf("%d", &number_in);
all_inputs[j] = number_in;
printf("\n");
printf("Enter the operation as + for add, - for substract, * for "
"multiply and / for division");
scanf(" %c", &operator_in);
all_inputs[j + 1] = operator_in;
}
printf("Enter the number : ");
scanf("%d", &number_in);
all_inputs[operator_entry + 1] = number_in;
for (int k = 0; k < (2 * how_many) - 1; k++)
printf("%s\n", all_inputs[k]);
return 0;
}
As you can see from the code, looping through the code to append inputs into the array is not working because I am doing
j=0
append a number to all_inputs[0]
append operator to all_inputs[0+1]
j=1
Now, the operator will be replaced with a number.
And another problem is, it shows "enter a number" just once and then loops the "enter the operator".
ss for problem
If you know any other way to do this, please let me know. Again, I am not a pro in C.
The purpose of my program thus far is to create 4 arrays. 1 'char' array which will take in 10 different string values with each element having a maximum of 25 characters. And 3 other array's that will take in 10 integer values and store them into my array. I compile and run my program, and cycle through my for loops and once completed, I get some weird integer values in the place of my teamName array, and for the 'teamWins' 'teamLosses' and 'teamTies' arrays, it gives me the first value I input for ALL elements in those arrays. I really want to understand how arrays work but I am having trouble declaring them, and using them with input, and output. Can anyone see and explain how I can take in 10 strings with values of 25 characters in each element, and take in 10 integers in the other 3 arrays with elements of 10? I will attach my source code below.
#include <stdio.h>
#include <stdlib.h>
#define NUM_TEAM 10
void displayWelcome(void);
int main(void)
{
char * teamName[NUM_TEAM + 1][30] = { "" };
int teamWins[NUM_TEAM] = {0};
int teamLosses[NUM_TEAM] = {0};
int teamTies[NUM_TEAM] = {0};
int i, bestPercent, worstPercent;
displayWelcome();
//Team Name
for (i = 0; i < NUM_TEAM; i++)
{
//Prompt and enter team name
printf("Enter %i's team name: ", i + 1);
fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);
//Data validation
}
//Team wins
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter wins for team number %i : ", i + 1);
scanf("%i", &teamWins[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamWins) || teamWins <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team losses
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter losses for team number %i : ", i + 1);
scanf("%i", &teamLosses[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamLosses) || teamLosses <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team ties
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter ties for team number %i : ", i + 1);
scanf("%i", &teamTies[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamTies) || teamTies <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Display Data
for (i = 0; i < NUM_TEAM; i++)/* output each word read */
{
printf("%s", teamName);
printf("wins losses ties\n");
printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);
}
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats\n\n");
}
You've got four issues:
Declaring teamName as char * teamName[NUM_TEAM + 1][30] = { "" }; is incorrect; if you want an array of strings, it's sufficient to declare char teamName[NUM_TEAM + 1][30] = { "" }; (you want a 2D array of chars, not char *s).
In fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);, you're writing each team name to the same unused element. Instead, use fgets (teamName[i], sizeof teamName[NUM_TEAM], stdin); to write to the proper team during each iteration.
Printing using printf("%s", teamName); is incorrect; you want to print each team name rather than attempt to print the address of the teamName array: printf("%s", teamName[i]);
You have an extra argument in printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);; since you've already printed teamName[i] in Point 3, you should remove it in this printf() call: printf("%i %i %i\n", teamWins[i], teamLosses[i], teamTies[i]);
so I'm fairly new to C and programming in general and also new to the website. Looking for guidance/help on figuring it all out, including help on how to properly use and ask questions on here.
So what I wanted to figure out is how to keep track of user defined numbers entered and also the value of the numbers added together. I was playing around with it for awhile looking for solutions, i was thinking there is a problem with my ways of keeping a count and not so much, there are no errors or warnings but the compiler stops after asking for an integer.
Any help or advice is much appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sumodd, sumeven, countodd, counteven;
char name;
printf("Please enter your name. \n");
scanf("%c", &name);
printf("Please enter an integer. \n");
do {
scanf("%d", &num);
if (num%2 == 0)
sumeven = sumeven + num;
counteven = counteven + num++;
if (num%2 == 1)
sumodd = sumodd + num;
countodd = countodd + num++;
} while (num > 0);
printf("%c, the numbers you entered are broken down as follows: \n", name);
printf("You entered %d even numbers with a value totaling at %d", counteven, sumeven);
printf("You entered %d odd numbers with a value totaling at %d", countodd, sumodd);
return 0;
}
As pointed out in comments you were doing some mistakes like:
Not initializing sumodd, sumeven, countodd, counteven to zero
Not using { } in if else blocks of odd even checking
Using a character for a name variable
adding num++ to count variables instead of 1, and thereby changing its value.
I modified your code slightly :
int num, sumodd = 0, sumeven = 0, countodd = 0, counteven = 0; // initialize to zero
char name[200];
printf("Please enter your name. \n");
scanf("%s", name);
printf("Please enter an integer. \n");
do {
scanf("%d", &num);
if (num%2 == 0) {
sumeven = sumeven + num;
counteven = counteven + 1;
}
if (num%2 == 1) {
sumodd = sumodd + num;
countodd = countodd + 1;
}
} while (num > 0);
printf("%s, the numbers you entered are broken down as follows: \n", name);
printf("You entered %d even numbers with a value totaling at %d\n", counteven, sumeven);
printf("You entered %d odd numbers with a value totaling at %d\n", countodd, sumodd);
When i ran it i was able to see desired output:
~/Documents/src : $ ./a.out
Please enter your name.
Rohan
Please enter an integer.
1
2
3
0
Rohan, the numbers you entered are broken down as follows:
You entered 2 even numbers with a value totaling at 2
You entered 2 odd numbers with a value totaling at 4
When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!
I have write a program that allows me to firstly enter a character c followed by an integer n and n float values representing grades. Using array to store the grades I have entered and no more than 100 grades can be introduced. The program allowed me to calculate the sum of the elements in array when I enter 's', compute the production of the elements in array when i enter 'p' and compute the average of the element s when i enter other words. After i enter the grades and character. The program has no response when i hit return to continue. So where is the mistake in my code
#include<stdio.h>
#include<stdio.h>
int main()
{
char c;
int integer_grade [100];
float floting_grade [100];
printf("Enter a grade");
scanf("%i,%f",&integer_grade[100],&floting_grade[100]);
int *a;
a=&integer_grade[100];
int *b;
b=&floting_grade[100];
printf("Enter a character");
getchar();
scanf("%c",&c);
int n;
switch(c)
{
case 's':
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("Sum is %d",*a+*b);
case 'p':
for (n=0;n=100;n++)
*a*=*a;
*b*=*b;
printf("Sum is %d",*a**b);
default:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("average is %d",(*a+*b)/100);
}
return 0;
}
The task is:
Write a program where you first enter a character c followed by an integer n and n float values representing grades. Use an array for storing the grades. You can assume that not more than 100 grades would be introduced. Yours program should compute and print the following: if c is 's' the sum of the grades, if c is 'p' the product of all grades and if another character was introduced then the arithmetic mean of all grades.
*use switch
*you can safely assume thee input will be valid.
Thoughts.
This is undefined behavior. You are assigning the read integer and float to offset 100 in those arrays, which doesn't exist.
int integer_grade[100];
float floting_grade[100];
scanf("%i,%f", &integer_grade[100], &floting_grade[100]);
These pointers point to memory that is outside the bounds of their respective arrays.
int *a = &integer_grade[100];
int *b = &floting_grade[100];
You ask for a character and then you ignore the value of that character:
getchar();
You then follow that up by getting the following character. Which is odd. But you do use the correct type and what not. So that's a win.
scanf("%c",&c);
Your indentation in these for loops implies that you think that both statements will be iterated on as part of the loop. That's incorrect. Use { ... } to accomplish that:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
I have no idea what you think you're accomplishing by *a += *a. I do know that the value at *a is going to grow quite quickly (and will likely overflow).
Switch statements use fallthrough on the cases. That means that if your case is 's', it will run all of the code in the switch statement, including all three cases. If you don't want this behavior, you should place break statements at the end of each case.
Please go back to your book / faculty / internet resource and read how a for loop works. This doesn't do what you probably think it does. In fact, this is an infinite loop!
for (n=0; n=100; n++)
Whatever do you try to do here, it's not right at all.
First: You declare 2 arrays of 100 elements, THEN you assign values outside of that array bounds (100 element array start from 0, finishes at 99)
Second: You create 2 pointers that points to outside of those array bounds.
Third: Inside the switch , the for (n=0;n=100;n++) is wrong, it should be something like for(n = 0; n < 100; n++)
Fourth: This
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
it would increment (if that for would be correct) only the first statement.
Correct way would be
for (n = 0; n < 100; n++)
{
*a += *a;
*b += *b;
}
Proper code would be
#include <stdio.h>
int main()
{
char c;
int integer_grade[100];
float floting_grade[100];
int nr_of_grades;
int i = 0;
printf("Enter number of grades: ");
scanf("%d", &nr_of_grades);
for(i = 0; i < nr_of_grades; i++)
{
printf("Enter a int grade: ");
scanf("%d", &integer_grade[i]);
printf("Enter a float grade: ");
scanf("%f", &floting_grade[i]);
}
int operation_i = 0;
float operation_f = 0;
printf("Enter a character");
scanf(" %c", &c);
int n;
switch(c)
{
case 's':
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Sums are Int: %d Float: %f", operation_i, operation_f);
case 'p':
operation_i = 1;
operation_f = 1;
for (n = 0; n < nr_of_grades; n++)
{
operation_i *= integer_grade[n];
operation_f *= floting_grade[n];
}
printf("Products are Int: %d Float: %f", operation_i, operation_f);
default:
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Average is Int: %d Float: %f", operation_i / nr_of_grades, operation_f / nr_of_grades);
}
return 0;
}