The goal is to assign the average to different players based on their uniform number. The problem is that it keeps skipping the second printf and the characters from the switch statement aren't working. I'm sure it's a pretty simple error on my part, but I just can't seem to find it.
int main(){
float ab;
float hits;
int un;
char pa;
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
while( un!= -1)
{
printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n");
scanf("%c%*c", &pa);
while(pa != 'E')
{
switch (pa)
{
case 'h':
case 'H':
ab += 1;
hits +=1;
break;
case 'o':
case 'O':
ab+=1;
break;
default:
printf("Error: Please insert an O or H \n");
break;
}
float average = (ab/hits);
printf("Player %d's score is equal to: %d \n", un, average);
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
}
}
return 0;
}
Your loop nesting wasn't quite correct, your scanf calls would hang, you needed to preinitialize ab and hits, and your final printf had an incorrect format.
Here's the corrected code [please pardon the gratuitous style cleanup]:
#include <stdio.h>
int
main()
{
float ab;
float hits;
int un;
char pa;
while (1) {
printf("Please enter the player number, or -1 to exit.\n");
#if 0
scanf("%d%*c \n", &un);
#else
scanf(" %d", &un);
#endif
if (un == -1)
break;
ab = 0;
hits = 0;
printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n");
while (1) {
#if 0
scanf("%c%*c", &pa);
#else
scanf(" %c", &pa);
#endif
if ((pa == 'E') || (pa == 'e'))
break;
switch (pa) {
case 'h':
case 'H':
ab += 1;
hits += 1;
break;
case 'o':
case 'O':
ab += 1;
break;
default:
printf("Error: Please insert an O or H\n");
break;
}
}
float average = (ab / hits);
#if 0
printf("Player %d's score is equal to: %d\n", un, average);
#else
printf("Player %d's score is equal to: %g\n", un, average);
#endif
}
return 0;
}
Related
I'm trying to make a C program that could read the students' scores until the user enter end of file (EOF) and determine whether their grade is A, B, C, D, or E. I'm having troubles in counting the total of A's, B's, C's, D's, and E's. The total is always 0 (zero).
This is what I've tried
#include<stdio.h>
int main()
{
int num_stu, score, counter, total,grade;
int aCount = 0, bCount=0, cCount=0,
dCount=0, eCount=0;
total = 0;
counter = 1;
printf("Enter how many number of students: ");
scanf("%d",&num_stu);
while (counter <=num_stu){
printf("Enter student score: ");
scanf("%d",&score);
if(score>=80)
printf("Student's grade is A\n");
else
if(score>=70)
printf("Student's grade is B\n");
else
if(score>=60)
printf("Student's grade is C\n");
else
if(score>=50)
printf("Student's grade is D\n");
else
printf("Student's grade is E\n");
counter=counter+1;
}
while ((grade=getchar()) !=EOF) {
switch (grade){
case 'A':case'a':
++aCount;
break;
case'B': case'b':
++bCount;
break;
case'C': case'c':
+cCount;
break;
case'D':case'd':
++dCount;
break;
case'E':case'e':
++eCount;
break;
case'\n': case' ':
break;
default:
printf("Incorrect letter grade entered.");
printf("Enter a new grade.\n");
break;
}
}
printf("\n Totals for each letter grade are: \n");
printf("A: %d\n",aCount);
printf("B: %d\n",bCount);
printf("C: %d\n",cCount);
printf("D: %d\n",dCount);
printf("E: %d\n",eCount);
return 0; }
Is there anything that I did wrong? Thanks in advance!
You need to get rid of '\n' every time you press enter. So to get rid of these Put
one getchar() before the while loop and one get char inside the while loop.
#include<stdio.h>
int main()
{
int num_stu, score, counter, total,grade;
int aCount = 0, bCount=0, cCount=0,
dCount=0, eCount=0;
total = 0;
counter = 1;
printf("Enter how many number of students: ");
scanf("%d",&num_stu);
while (counter <=num_stu){
printf("Enter student score: ");
scanf("%d",&score);
if(score>=80)
printf("Student's grade is A\n");
else
if(score>=70)
printf("Student's grade is B\n");
else
if(score>=60)
printf("Student's grade is C\n");
else
if(score>=50)
printf("Student's grade is D\n");
else
printf("Student's grade is E\n");
counter=counter+1;
}
getchar();
while ((grade=getchar()) !=EOF) {
getchar();
switch (grade){
case 'A':case'a':
++aCount;
break;
case'B': case'b':
++bCount;
break;
case'C': case'c':
+cCount;
break;
case'D':case'd':
++dCount;
break;
case'E':case'e':
++eCount;
break;
case'\n': case' ':
break;
default:
printf("Incorrect letter grade entered.");
printf("Enter a new grade.\n");
break;
}
}
printf("\nTotals for each letter grade are: \n");
printf("A: %d\n",aCount);
printf("B: %d\n",bCount);
printf("C: %d\n",cCount);
printf("D: %d\n",dCount);
printf("E: %d\n",eCount);
return 0;
}
I am working on an accumulator that asks for different inputs and based on those inputs, updates values in an accumulator. My loop however, doesn't seem to run when I ask for a decimal, hexadecimal, or octal to be inputed. Could someone possibly take a look and give some suggestions to fix it? Thank you! Also Im suppose to somehow use a while loop in my print_menu() function that will check is the input is valid. Any suggestions?
#include <stdio.h>
#include <string.h>
short get_operand(char mode);
void print_acc(short acc);
char print_menu(void);
int main(void);
int main(){
char mode = 'D';
short acc = 8;
char input[10];
char option;
char valid_input[7] = "OHDCSQ";
while (mode != 'Q'){
print_acc(acc);
print_menu();
scanf("%s", &input);
printf("%s\n", input);
option = (char) toupper(input[0]);
switch(option){
case 'O':
mode = 'O';
printf("mode\n");
printf("Mode is Octal\n");
break;
case 'H':
mode = 'H';
printf("Mode is Hexadecimal\n");
break;
case 'D':
mode = 'D';
printf("Mode is Decimal\n");
break;
case 'C':
acc = 0;
break;
case 'S':
get_operand(mode);
if (mode == 'H'){
scanf("%hx", &acc);
printf("%hx", acc);
print_acc(acc);
}
else if (mode == 'O'){
scanf("%ho", &acc);
printf("%ho", acc);
print_acc(acc);
}
else{
scanf("%hd", &acc);
printf("%hd", acc);
print_acc(acc);
}
case 'Q':
mode = 'Q';
printf("\n");
break;
}
//return acc;
}
}
void print_acc(short acc){
printf("\n");
printf("****************************************\n");
printf("* Accumulator: *\n");
printf("* Hex : %04hx *\n", acc);
printf("* Octal : %08ho *\n", acc);
printf("* Decimal : %06hd *\n", acc);
printf("****************************************\n");
}
char print_menu(void){
printf("\n");
printf("Please Select one of the following options:\n");
printf("O Octal Mode\n");
printf("H Hecadecimal Mode\n");
printf("D Decimal Mode\n");
printf("\n");
printf("C Clear Accumulator\n");
printf("S Set Accumulator\n");
printf("\n");
printf("Q Quit\n");
printf("\n");
printf("Option: ");
}
short get_operand(char mode){
switch(mode){
case 'H':
printf("Enter Hex value:");
break;
case 'O':
printf("Enter Octal value:");
break;
default:
printf("Enter decimal value: ");
break;
}
return mode;
}
In the 'S' case where you read in a number, you forget to add a break statement at the end of the case. This results in the code falling through to the Q case which causes the loop to exit.
Add the break and the loop will continue as expected:
case 'S':
...
break;
case 'Q':
...
This is also incorrect:
scanf("%s", &input);
%s expects a char *, but you're passing the address of an array (a char (*)[10] to be presice). Pass in the array directly, which will decay to a pointer to the first element to yield the correct type:
scanf("%s", input);
Also, change print_menu and get_operand to return void, since you're not using the return value and in the former case failing to include one.
i'm currently learning C, and i have an exercise, request for 20 characters and show the amount of ('a','e','i','o','u').
I coded this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char letter;
int a = 0, e = 0, i = 0, o = 0, u = 0, x;
for(x = 0; x < 20; x++)
{
printf("\nEnter a character: ");
letter = getchar();
letter = tolower(letter);
switch(letter)
{
case 'a':
a += 1;
break;
case 'e':
e += 1;
break;
case 'i':
i += 1;
break;
case 'o':
o += 1;
break;
case 'u':
u += 1;
break;
default:
continue;
}
system("cls");
}
printf("\nAmount of 'a': %d", a);
printf("\nAmount of 'e': %d", e);
printf("\nAmount of 'i': %d", i);
printf("\nAmount of 'o': %d", o);
printf("\nAmount of 'u': %d\n", u);
system("pause");
return 0;
}
But this only can be executed 10 times. Why this happens?
PD. Sorry for my poor english.
As mentioned in the comments, you are processing 20 characters, but half of them are newlines. If you take out your line system("cls") this becomes apparent:
% ./ctest
Enter a character: a
Enter a character:
Enter a character: b
Enter a character:
Enter a character: c
At the first prompt, I typed a<RET> and the first loop iteration (x=0) processed the a but there is still a <RET> waiting in the input buffer. The second loop iteration (x=1) gets the next available character, <RET> and processes it, the the third loop iteration (x=2) prints its prompt and waits for new input.
You can further see how this works by getting it to process 20 characters you are counting. For example, if I provide the input aaaaaeeeeeiiiiiooooo<RET>, which is 21 characters, you can see that the first 20 are processed:
% ./ctest
Enter a character: aaaaaeeeeeiiiiiooooo
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Amount of 'a': 5
Amount of 'e': 5
Amount of 'i': 5
Amount of 'o': 5
Amount of 'u': 0
To fix this problem you should either read and discard the newline character or use a different method of reading that can ignore the newlines.
You need to ignore newline chars.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char letter;
int a = 0, e = 0, i = 0, o = 0, u = 0, x;
for (x = 0; x < 20; x++)
{
printf("\nEnter a character: ");
letter = getchar();
letter = tolower(letter);
if (letter == '\n')
{
x--;
system("cls");
continue;
}
if (letter)
{
switch (letter)
{
case 'a':
a += 1;
break;
case 'e':
e += 1;
break;
case 'i':
i += 1;
break;
case 'o':
o += 1;
break;
case 'u':
u += 1;
break;
default:
break;
}
}
system("cls");
}
printf("\nAmount of 'a': %d", a);
printf("\nAmount of 'e': %d", e);
printf("\nAmount of 'i': %d", i);
printf("\nAmount of 'o': %d", o);
printf("\nAmount of 'u': %d\n", u);
system("pause");
return 0;
}
You can use scanf instead of getchar, it will also solve it.
i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}
I can't seem to get this program to compile.
I keep getting the error:
'Ammonia' undeclared 'Carbon_Monoxide' undeclared
and so on. Am I using the right function with switch?
/*This program will report the content of a compressed-gas cylinder based on the first letter of the cylinder's color.*/
#include <stdio.h>
int main (void)
{
int x;
char o, b, y, g;
int pause;
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%d", &x);
switch (x)
{
case 'o': printf("The content is Ammonia\n");
case 'b': printf("The content is Carbon Monoxide\n");
case 'y': printf("The content is Hydrogen\n");
case 'g': printf("The content is Oxygen\n");
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf("%d", &pause);
return 0;
}
It has nothing to do with your switch statement, but you will probably have to puzzle over the meaning of these four lines:
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
You don't use the variables thus defined anywhere, and the symbols "Ammonia", "Carbon_Monoxide" and so on are not defined - this is the cause of the error you are seeing.
Since this is homework, I don't want to give you the answer straight, but look at what you're doing with those chars (o, b, y, g) and ask yourself if it makes sense.
Also, on the switch statement, I'm pretty sure you need a break; after each case, else it will print each case's statement
try:
#include <stdio.h>
int main (void)
{
char x;
int pause;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%c", &x);
while(x){
switch (x)
{
case 'o': printf("The content is Ammonia\n"); break;
case 'b': printf("The content is Carbon Monoxide\n"); break;
case 'y': printf("The content is Hydrogen\n"); break;
case 'g': printf("The content is Oxygen\n"); break;
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf(" %c", &x);
if(x == 'q'){
break;
}
}
return 0;
}