C Program Won't End When User Enters Invalid Character [duplicate] - c

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 4 years ago.
I'm trying to write a C program that computes X^Y (X to the Y power) without using the 'pow' function. The program works fine when I enter numbers, but I'm having an issue with the code not stopping when the user enters a character that isn't a number. It runs through the program once more after giving the message "The character you have entered is not a number.Please try again.The character you have entered is not a number.Please try again. The value is 1." Can someone help? I'm going insane trying to figure this out.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
if (y!=1)
printf("The character you have entered is not a number.Please try again.");
else
for(i=1;i<=y;i++)
{
val=x;
n=n*val;
}
printf("The value is %d.\n", n);
return 0;
}

When your program detects invalid input, it prints a message, but otherwise just continues on ahead as if a valid input had been read. Instead, it needs to do one of these things:
abort when invalid input is detected, or
consume and ignore the invalid input, AND
loop back to provide a chance to enter new input, or
use a default value.
Its message suggests that the program will provide for entering new input, but in fact it does not follow through. Moreover, if it is the input for the first prompt that is invalid, then that input is still waiting to be read when the program prints the second prompt, where it is still invalid, and the program blithely continues on a second time, ultimately printing the initial value of n, 1, without having calculated anything.

You need to check how many items scanf successfully read:
int numItemsRead = 0;
printf("What power is the number raised to?\n");
numItemsRead = scanf("%d", &y);
if (numItemsRead!=1)
printf("The character you have entered is not a number.Please try again.");
} else {
'''
}

int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
return 0;
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
Maybe if u do like that even if u entered a invalid character program will be end.

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.

Having a problem with a function in my C program. Program terminates before executing the second last "printf()" in the "encript()" function

When I call "encript()", it works how I want it to until the second last "printf()" at which point the program terminates without executing any more lines. I tried searching for similar questions here and tried to fix my code but nothing that I could find seemed to work.
I am a beginner so please forgive me if it's just a simple mistake.
char encript(int x){
printf("You selected Encription with the key: %d\n\n", x); //Tells user the key value they input
Sleep(1000);
int msglength = 100; //Variable for the amount of characters in the messge
printf("\n\nEnter aproximate number of characters in you message. \nThe number must be at least 1 over the amount of characters in your message: ");
scanf("%d", msglength); //assigns user input integer to msglength
printf("\n\n");
char message[msglength]; //Creates a character array for the message with a length of "msglength"
printf("Insert message here: "); ////THIS LINE DOES NOT SEEM TO EXECUTE. NOR DO THE TWO BELOW IT.
scanf("%s", message);
printf("\n\n%s", message);
}
Thanks!
pay attention to this line scanf("%d", msglength); , for scanning variables you should send their address to scnaf , so this should be scanf("%d", &msglength);(add & to scanf)
this function should return a character ,if you just want to to scan a message and print it , you should use void like this void encript(int x) also if you want to return message you can use char * encript(int x) .

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/

getchar not working in switch case (c)

Using a very simple calculator program that prompts a user for an operation to perform, followed by a prompt for two integers on which to perform this operation. The program is supposed to loop after these operations, except in the case where the user enters the character 'q', at which point the program is supposed to quit.
#include <stdio.h>
int main (void)
{
char c;
int number[2], num1, num2, result;
double num1d, num2d, resultd;
int done=1;
while(done)
{
printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
c = getchar();
printf("\tplease enter a number \n");
scanf("%d",&number[0]);
printf("\tplease enter another number \n");
scanf("%d",&number[1]);
num1 = number[0];
num2 = number[1];
switch(c)
{
case('-'):
result = num1-num2;
printf("\nThe first number you entered subtracted by the second number is %d.\n", result);
break;
case('+'):
result = num1+num2;
printf("The first number you entered added to the second number is %d.\n", result);
break;
case('*'):
result = num1*num2;
printf("The first number you entered multiplied with the second number is %d.\n", result);
break;
case('/'):
num1d = (double) num1;
num2d = (double) num2;
resultd = num1d/num2d;
printf("The first number you entered divided by the second number is %g.\n", resultd);;
break;
case('q'):
printf(" Now Exiting...\n");
done=0;
break;
default:
puts("Invalid key pressed. Press q to exit");
break;
}
}
return 0;
}
Works correctly for a single calculation, but subsequently performs oddly; in particular it prints
printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
printf("\tplease enter a number \n");
altogether.
The standard method of clearing the input buffer while (getchar() != '\n'); doesn't fix this. One out of two times that this text displays incorrectly the user can still use the program as if the instructions were displaying as they should (so the user can type an operation such as +, carriage return, and then some integer and a carriage return, and the program will perform correctly from that point on) Every other time however the program will put "Invalid key pressed. Press q to exit" regardless of input.
What everyone else here is saying is true, getchar() returns an int but that's not your problem.
The problem is that getchar() leaves a newline character after you use it. If you're going to use getchar() you must always consume the newline char afterwards. This simple fix:
printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n");
c = getchar();
getchar(); //<-- here we do an extra getchar for the \n
printf("\tplease enter a number \n");
scanf("%d",&number[0]);
printf("\tplease enter another number \n");
scanf("%d",&number[1]);
and that will eliminate the problem. Every time you type <somechar><enter> it's really putting two characters on the buffer, for example if I hit + and enter I'm getting:
'+''\n' // [+][\n]
getchar() will only get the first of these, then when getchar() is called again it won't wait for your input it will just take that '\n' and move on to the scanf()
You shouldn't mix character-by-character with more high-level input functions such as scanf(). It's better to use scanf() to input the command character too, but of course then you will have to press enter after the command. I believe this it the root cause of your problems.
As an aside, note that getchar(), despite it's name, returns int, not char. This is because it can return EOF which is a special constant whose value is different from that of all characters.
Further, you should always check the return value of I/O functions like scanf(), they can fail if the input doesn't match the pattern string.
As a debugging hint, you can of course print the value of c before interpreting it, so you can easier see and understand the flow of the program.
I'm guessing it works the first time, but not the next time. This is because the scanf calls leaves the newline in the input buffer so the next time getchar is called in the loop it will return the newline character. Add a space after the format in the scanf calls
scanf("%d ",&number[0]);
and it will discard remaining whitespace from the buffer.
Use a debugger to step through the code and check the variables to verify.
Your getchar should return int. The reason is as below
getchar reads characters from the program's standard input
and returns an int value suitable for storing into a char.
The int value is for one reason only: not only does getchar
return all possible character values, but it also returns an
extra value to indicate that end-of-input has been seen.
The range of a char might not be enough to hold this extra value,
so the int has to be used.
So basically you need to change char c to int c in your code

A simple program in C, need some input

I'm trying to write a simple program where it ask user to enter a bunch of positive integers, and calculate the average of all the number entered. Program will terminate when user enter a non positive number like 0 or -1.
Here is my code. For some reason I get an error right when I try to enter the first input, can someone help?
#include <stdio.h>
int main()
{
int input=0, sum=0,average=0,i=0;
printf("Please enter positive numbers, enter 0 or -1 to end:\n");
scanf("%d",input);
while (input>0)
{
sum+=input;
i++;
scanf("%d",input);
}
average=sum/i;
printf("The average is %d",average);
}
You need to pass the address of the variable to scanf.Try this:
scanf("%d", &input);
^
Also see the C FAQ: Why doesn't the call scanf("%d", i) work?

Resources