Getting zero answer while using DO-WHILE loop - c

I tried to calculate the tot(total fee) in the do-while loop, but all I get is tot=0.00?! Why is this happening? And after that I get a message: it said the variable fee is not being initialised?
#include<stdio.h>
int main(void)
{
int cofno;
float tot=0.0;
float fee;
char option;
do{
printf("Enter cofno: ");
scanf("%d",&cofno);
if(cofno>0)
{
printf("Key in (h/c): ");
scanf("%c",&option);
getchar();
switch(option)
{case 'h':fee=cofno*1.80;
break;
case 'c': fee=cofno*2.50;
break;
}
tot=tot+fee;
//the program will repeat until the user key in negative value or zero
}
}while(cofno>0);
printf("\ntot=RM%.2f \n\n",tot);
return 0;
}

scanf(" %c",&option); This will solve the problem for you. The reason the ' ' is provided in the scanf so that it can consume the white space characters.
What happened earlier was that your character input got the \n from previous input.
To check the thing that it inputted \n try outputting the option like this
printf("[%c]",option); you will see output
[
]
Also the break statement you provide is breaking for the case staement. Not the while loop. You have infinite loop now. You can solve this with a added condition.
...
tot=tot+fee;
if(option == 'c' || option =='h')
break;
...
Even more simply, you could have changed the while condition overall and make it like this
while(cofno<=0);
this conforms to your idea the program will repeat until the user key in negative value or zero more suitably.

Related

isdigit() and system("cls") produce infinite loop

I was at first having trouble with a scanf() function being skipped, but I fixed that by adding in a space before %c in the scanf() function.
When trying to ask for input from the user as to whether the screen should be cleared, the scanf(" %c", cClear); conversion specifier gives an infinite loop, it is expecting a character, but responds to input as if not a character.
I believe it may have something to do with my input buffer.
I tried to use fflush(stdin) to no avail, I also used printf("%d", (int) cClear); to see the output, which was zero.
One other problem I have is trying to check user input for a digit.
I use:
if (isdigit(iSelection) == 0) {
printf("\nPlease select a valid numerical value.\n");
continue;
to check user input and restart the while loop, but anytime a character is entered and not an integer, I get an infinite loop.
My goal is to give the user the option to clear the screen after each calculation, and to also check input for being a digit.
Any help is appreciated.
//excluding code prior to main() and function definitions
int main(void) {
int iSelection = -1;
double foperand1 = 0, foperand2 = 0;
int ioperand1 = 0, ioperand2 = 0;
char cClear = '\0';
while (iSelection) {
printf("\n\nTHE CALCULATOR\n");
printf("\nCalculator menu:\n");
printf("\n1\tAddition");
printf("\n2\tSubtraction");
printf("\n3\tMultiplication");
printf("\n4\tDivision");
printf("\n5\tModulus (Integers only)");
printf("\n6\tTest if Prime (Integers only)");
printf("\n7\tFactorial (Integers only)");
printf("\n8\tPower");
printf("\n9\tSquare Root");
printf("\n0\tExit\n");
printf("\nPlease enter your selection: ");
scanf("%d", &iSelection);
//here we check for if input was a digit
if (isdigit(iSelection) == 0) {
printf("\nPlease select a valid numerical value.\n");
continue;
switch(iSelection) {
case 0:
break;
case 1:
printf("\nEnter the two numbers to add seperated by a space: ");
scanf("%lf %lf", &foperand1, &foperand2);
printf("\n%.5lf + %.5lf = %.5lf\n", foperand1, foperand2, addNumbers(foperand1, foperand2));
break;
}
//here we ask the user if they want to clear the screen
fflush(stdin)
if (iSelection != 0) {
printf("\nDo you want to clear the screen? ('y' or 'n'): ");
scanf("%c", cClear);
//printf("%d", (int) cClear); //used this to help debug
//scanf("%d", iSelection);
if (cClear == 'y')
system("cls");
}
}
printf("\nExiting\n");
return 0;
}
one error I get is "system" is declared implicitely. Could it possibly be the windows operating system not recognizing the pre defined function call?
Thanks to the people who commented to help me figure this out.
I had forgotten to add the (&) to the scanf() function call for the system"cls" function call, as well as didn't include the correct library (stdlib.h).
I was also able to make the program stop skipping the scanf() function by adding a space to the " %c" conversion specifier.
scanf Getting Skipped
I was able to make the isdigit() function work by changing the variable 'iSelection' to a character, but then I also had to change my case values to characters, not integers.

Why is my default case statement repeating twice before allowing me to scanf?

i have put down below a small function to check which char the user type. the 'y' and 'n' works fine but i am a bit confused as to why my c code repeats twice before allowing me to type again when i input a different character which i put as my default statement.
int any_size_array () {
int a=19;
int numb_array [] = {a,22,13,132,153,600};
printf("do you want to add more numbers to the array?\t");
char user;
scanf("%c", &user);
switch(user) {
case 'y':
printf("user typed %c\n", user);
break;
case 'n':
printf("user typed %c\n", user);
break;
default:
printf("please try again\n");
any_size_array();
}
Because \n is a character, and %c does not consume it. If you want to skip whitespace, try scanf(" %c", &user).
Also, you must always check the value returned by scanf. If scanf does not modify the value of user, then your program is invoking undefined behavior by attempting to read from an uninitialized variable. Try:
if( scanf(" %c", &user) == 1 ) { ... }
Do not use recursion. Every time you call the any_size_array() function all variables are created again and are not related. Use loops for that.
Your input has more chars than only the character entered. (new line for example)

switch always default after I input data

Maybe there is no problem in running the first code
However,it will always default after I enter comment's data
char answer;
do{
printf("Do you want to add new comment?Y/N: ");
scanf("%c",&answer);
fflush(stdin);
switch(tolower(answer))
{
case 'y':
comment();
break;
case 'n':
main();
break;
default:
printf("Wrong choice !\n\n");
break;
}
}while(tolower(answer)!=='y'||'n');
there is the code of comment(),I guess the problem at here.
FILE*fp=fopen("comment.txt","a+");
if(fp == NULL)
{
printf("FIle not Found");
exit(1);
}
else
{
printf("Please enter your name: ");
gets(c.name);
printf("Pleas enter the date: ");
gets(c.date);
printf("Please enter the movie name: ");
gets(c.movie);
printf("Please enter your comment in 100 words:\n");
printf("Please press [Tab]and[Enter] to submit your comment\n");
scanf("%[^\t]",c.comment);
fprintf(fp,"%s %s\n%s\n%s\n\n",c.name,c.date,c.movie,c.comment);
}
fclose(fp);
Can someone help me?Thx!!
try using strlwr() instead of tolower()
Compiler gives you no error for while condition?
Maybe you want to write:
while(tolower(answer)!='y'||tolower(answer)!='n');
Inside do{}while you are reading input buffer which has a character you entered and a enter key. You need to clear that. Try scanf("%c%*c",&answer); .which will read that extra character from the buffer
A couple of problems in your code.
scanf("%c",&answer);
When you enter a character for the first time and if the character if either y or n then in next iteration this scanf() will read the stray \n (newline) character from the input buffer. To overcome this problem, add a space character before %, like this:
scanf(" %c",&answer);
Another problem is this statement:
while(tolower(answer)!=='y'||'n');
^^ ^
The compiler must be giving you both error and warning in this statement.
Change this to:
while(tolower(answer)=='y'||tolower(answer)=='n');
With this the loop to be run till user give input either y or n and for any other character, the loop will exit.
If you don't want loop to exit for any input character other then y or n but just print the message Wrong choice ! message then you can do:
}while(tolower(answer)!='y'||tolower(answer)!='n');

How to enter a letter to quit a program in C

I am new to C programming. I have been writing this code to add numbers and I just need help with this one thing. When I type the letter 'q', the program should quit and give me the sum. How am I supposed to do that? It is currently the number 0 to close the program.
#include <stdio.h>
int main()
{
printf("Sum Calculator\n");
printf("==============\n");
printf("Enter the numbers you would like to calculate the sum of.\n");
printf("When done, type '0' to output the results and quit.\n");
float sum,num;
do
{
printf("Enter a number:");
scanf("%f",&num);
sum+=num;
}
while (num!=0);
printf("The sum of the numbers is %.6f\n",sum);
return 0;
}
One approach would be to change your scanf line to:
if ( 1 != scanf("%f",&num) )
break;
This will exit the loop if they enter anything which is not recognizable as a number.
Whether or not you take this approach, it is still a good idea to check the return value of scanf and take appropriate action if failed. As you have it now, if they enter some text instead of a number then your program goes into an infinite loop since the scanf continually fails without consuming input.
It's actually not as straightforward as you'd think it would be. One approach is to check the value returned by scanf, which returns the number of arguments correctly read, and if the number wasn't successfully read, try another scanf to look for the quit character:
bool quit = false;
do
{
printf("Enter a number:");
int numArgsRead = scanf("%f",&num);
if(numArgsRead == 1)
{
sum+=num;
}
else // scan for number failed
{
char c;
scanf("%c",&c);
if(c == 'q') quit = true;
}
}
while (!quit);
If you want your program to ignore other inputs (like another letter wouldn't quit) it gets more complicated.
The first solution would be to read the input as a character string, compare it to your character and then convert it to a number later. However, it has many issues such as buffer overflows and the like. So I'm not recommending it.
There is however a better solution for this:
char quit;
do
{
printf("Enter a number:");
quit=getchar();
ungetc(quit, stdin);
if(scanf("%f", &num))
sum+=num;
}
while (quit!='q')
ungetc pushes back the character on the input so it allows you to "peek" at the console input and check for a specific value.
You can replace it with a different character but in this case it is probably the easiest solution that fits exactly what you asked. It won't try to add numbers when the input is incorrect and will quit only with q.
#Shura
scan the user input as a string.
check string[0] for the exit condition. q in your case
If exit condition is met, break
If exit condition is not met, use atof() to convert the string to double
atof() reference http://www.cplusplus.com/reference/cstdlib/atof/

do-while loop "enter more (y/n)" - character issue

So I'm working on basic C skills, and I want to design a code which enters as many numbers as the user wants. Then, it should display the count of positive,negative & zero integers entered.
I've searched Google & StackOverflow. The code seems fine according to those programs.
It compiles & runs. But whenever I input anything after the prompt "enter more? y/n", it returns to the code..
Please have a look at the code below:
#include<stdio.h>
int main()
{
int no,count_neg=0,count_pos=0,count_zero=0;
char ch='y';
clrscr();
do
{
puts("Enter number");
scanf("%d",&no);
if (no>0)
count_pos++;
else if (no<0)
count_neg++;
else
count_zero++;
puts("want more? - y/n ");
scanf("%c",&ch);
}
while (ch=='y');
if (ch=='n')
{
printf("No of positives = %d",count_pos);
printf("No of negatives = %d",count_neg);
printf("No of zeros = %d",count_zero);
}
getch();
return 0;
}
The problem is with "scanf("%c", &ch);"
What happens actually is :
Suppose you enter 'y' as a choice and hit 'enter'(return), the return is a character and
its character value is 10(since its a new line character), thus the scanf takes the 'return'
as its input and continues.
Solution :
1. use getchar() before scanf()
// your code
getchar();
scanf();
//your code
getchar() takes the return value as its input, thus you are left with your actual value.
add '\n' to scnaf()
// code
scanf("\n%c", &ch);
//code
when scanf() encounters the '\n' character it skips it (google about scanf, to know how
and why ), thus stores the intended value inside 'ch'.
A "better" form for:
int main()
is:
int main(void)
clrscr is not standard C.
You ought to check the return-value of any function which might indicate "interesting status," such as a failure condition, and from which you can gracefully deal with the situation. In this case, scanf is such a function.
I believe that your first do ... while condition will become false because it will pick up the newline character following your first scanf call. You might want to read about getchar or getc, instead of using scanf for the task of checking whether or not to run the loop again. You can "eat" unwanted characters, including a newline.
Here, I have corrected the problem. The problem was this that the "enter" you press after each number is a character and is takenup by the scanf() as it is there to scan some characters. So I have added a getchar(); before the scanf();so the "enter" is taken up by getchar(); and scanf() is now free to take your input.
#include<stdio.h>
int main()
{
int no,count_neg=0,count_pos=0,count_zero=0;
char ch='y';
clrscr();
do
{
puts("Enter number");
scanf("%d",&no);
if(no>0)
count_pos++;
else if(no<0)
count_neg++;
else
count_zero++;
puts("want more? - y/n ");
getchar();//<---- add this here
scanf("%c",&ch);
}
while(ch=='y');
if(ch=='n')
{
printf("No of positives = %d",count_pos);
printf("No of negatives = %d",count_neg);
printf("No of zeros = %d",count_zero);
}
getch();
return 0;
}
To fix the input is to use a C String like this scanf("%s",...);
This might break if you input more than one character because scanf will keep reading until the user hits enter, and your ch variable is only enough space for one character.
I run your code in Online compiler. I am not sure about other compiler.
I slightly changed your code. i.e., first i read char then int. If i do not change the order, char variable holds int variable value. This is the reason ( ch variable holds values of no variable).
#include<stdio.h>
int main()
{
int no,count_neg=0,count_pos=0,count_zero=0;
char ch='y';
do
{
puts("Enter number");
scanf("%c",&ch);
scanf("%d",&no);
if(no>0)
count_pos++;
else if(no<0)
count_neg++;
else
count_zero++;
puts("want more? - y/n ");
}
while(ch=='y');
if(ch=='n')
{
printf("No of positives = %d",count_pos);
printf("No of negatives = %d",count_neg);
printf("No of zeros = %d",count_zero);
}
return 0;
}
EDIT:
whenever integer and char are read through keyboard. it stores int value and enter key value. so this is the reason.
You have to add
scanf("%d",&no);
you code
......
.....
fflush(stdin);
scanf("%c",&ch);
use:
ch = getche();
instead of:
scanf("%c", &ch);

Resources