So here is my code. Its a school assignment. I had to make a program to calculate the square root of a number using a method the Babylonians developed etc, that's not the important part. What I was wondering is if it's possible to ignore letters in my scanf so that when I input a letter it doesn't go berserk in my terminal. Any help is welcome and greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double root_Approach(double s); // defines the two functions
void ask_Number(void);
int main() {
ask_Number(); // calls function ask_Number
printf("\n\n");
system("pause");
return 0;
}
double root_Approach(double s) {
double approach;
approach = s;
printf("%.2lf\n", s); // prints initial value of the number
while (approach != sqrt(s)) { // keeps doing iteration of this algorithm until the root is deterimened
approach = (approach + (s / approach)) * 0.5;
printf("%lf\n", approach);
}
printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes
return approach;
}
void ask_Number(void) {
double number;
while (1) {
printf("Input a number greater than or equal to 0: "); // asks for a number
scanf_s("%lf", &number); // scans a number
if (number < 0) {
printf("That number was less than 0!!!!!!\n");
}
else {
break;
}
}
root_Approach(number);
}
Scanf reads whatever may be the input from the terminal (character or integer)
One way you can do is to check the return statement of scanf whether the read input is integer or not an integer.
Here is the sample code
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
`
this link may be helpful
Check if a value from scanf is a number?
Related
#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.
I need help with error checking for my program. I'm asking the user to input a integer and I would like to check if the users input is a integer. If not, repeat the scanf.
My code:
int main(void){
int number1, number2;
int sum;
//asks user for integers to add
printf("Please enter the first integer to add.");
scanf("%d",&number1);
printf("Please enter the second integer to add.");
scanf("%d",&number2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0){
printf("The sum of these two integers is a multiple of 3!\n");
}else {
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
scanf returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2); returns 1. The trick, however, is to ignore invalid data when scanf returns zero, so the code would look like this:
while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}
Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main to avoid duplication.
Here is a solution of your problem. I just modified some of your code.
Read comments for any explanations.
#include<stdio.h>
#include<stdlib.h> //included to use atoi()
#include<ctype.h> //included to use isalpha()
#define LEN 3 //for two digit numbers
int main(void)
{
char *num1=malloc(LEN);
char *num2=malloc(LEN);
int i,flag=0;
int number1,number2;
int sum;
do
{
printf("Please enter the first integer to add = ");
scanf("%s",num1);
for (i=0; i<LEN; i++) //check for every letter of num1
{
if (isalpha(num1[i])) //isalpha(num1[i]) returns true if num1[i] is alphabet
{ //isalpha() is defined in ctype.h
flag=1; //set flag to 1 if num1[i] is a alphabet
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
do
{
printf("Please enter the second integer to add = ");
scanf("%s",num2);
for (i=0; i<LEN; i++)
{
if (isalpha(num2[i]))
{
flag=1;
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
//strings to integers
number1= atoi(num1); //atoi() is defined in stdlib.h
number2= atoi(num2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0)
{
printf("The sum of these two integers is a multiple of 3!\n");
}
else
{
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
I designed this for only two digit numbers, but it is working fine for more than two digit numbers for me.
Please let me know that same is happening in your case.
And if you will find why this is happening please comment.
And you can also use strtol() instead of atoi(). I am not using it because of small values.
Difference between atoi() and strtol()
atoi()
Pro: Simple.
Pro: Convert to an int.
Pro: In the C standard library.
Pro: Fast.
Con: No error handling.
Con: Handle neither hexadecimal nor octal.
strtol()
Pro: Simple.
Pro: In the C standard library.
Pro: Good error handling.
Pro: Fast.
Con: Convert to a long, not int which may differ in size.
I would like to say that you have to make some custom validation to check if whether scanf read integer or not.I am used fgets not interested in scanf.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) ) return 1;
return 0;
}
int main ( void )
{
int i;
char buffer[BUFSIZ];
printf ( "Enter a number: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
buffer[strlen ( buffer ) - 1] = '\0';
if ( validate ( buffer ) == 0 ) {
i = atoi ( buffer );
printf ( "%d\n", i );
}
else
printf ( "Error: Input validation\n" );
}
else
printf ( "Error reading input\n" );
return 0;
}
A clean approach to this problem can be
read from stdin using fgets().
use strtol() to convert and store the value into an int. Then check for the char **endptr to determine whether the conversion is success [indicates integer] or not.
Perform remaining task.
Here's my code:
#include <stdio.h>
#include <ctype.h>
main(){
float input;
printf("Input: ");
scanf("%f", &input);
if (isalpha(input) || (input) < 0)){
printf("Input is an alphabet or is lesser than 0");
} else {
printf("Input is correct. %f is a number larger than 0", input);
}
}
I want the code to detect if input is a number larger than 0, or is it an alphabet. However, I am getting this error:
8: error: identifier expected
What does it mean to my code's execution? How am I supposed to run the code successfully?
Correct parentheses in if:
if ( isalpha(input) || (input < 0) )
In addition, you need to check the return value of scanf() whether there was input or not. In the case of no input, the return value would be 0 or in case of multiple inputs how many succeeded. In your case, you can use the return value to determine whether a float was input or not.
The main() should return an int and always initialize your variables.
Example (live):
#include <stdio.h>
#include <ctype.h>
int main()
{
float input = 0.0f;
printf("Input: ");
int ret = scanf("%f", &input);
if ( ret == 0 )
{
printf("ERROR: Input is NOT a float!\n");
return -1;
}
if ( input < 0.0f )
{
printf("Input is less than 0");
}
else
{
printf("Input is correct. %f is a number larger than 0", input);
}
return 0;
}
Your parentheses aren't opened/closed properly.
Maybe your ide/compiler is taking care of it, but it should be int main()
isalpha() will behave unexpectedly with float values. Try avoiding that.
First of all you are missing int declaring main,
int main()
Also,you have excessive bracket in line
if (isalpha(input) || (input) < 0)){
Scanf uses %f to read floats. What your program will do is accept any ascii character and I suppose that wasn't your intention.
I am still not sure what you need, but you could try something like this as a starting point. It does not handle all possible inputs, and will erroneously classify an input such as #42 as alphabet or lesser than 0, which is questionable, but you can iterate on this and hopefully get to a more polished version.
#include <stdio.h>
#include <ctype.h>
int main(){
float input;
printf("Input: ");
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
} else {
printf("Input is an alphabet or is lesser than 0");
}
}
Explanation
We save the value in input, if compatible with the %f format:
float input;
Prompt for the user:
printf("Input: ");
This condition is made of two parts; the first part is the scanf, that will try to read input, and if successful will evaluate to 1, which is true, so the second part input >= 0 will be evaluated, and if input is indeed >= 0 we print the first message.
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
Else we print the second message.
} else {
printf("Input is an alphabet or is lesser than 0");
}
I am learning c language and i am confused about the code below. its a recursion but how come when i run this code, it won't run until i provided 2 different inputs but system only execute the first?
Thanks in advance.
#include <stdio.h>
long factor (float user_input)
{
if(user_input <=1)
return 1;
else
return (user_input * factor (user_input - 1));
}
int main ()
{
int user_input;
long factorial_calculation;
printf("what factorial number would you like to calculate?\n");
scanf("%d\n", &user_calculation);
factorial_calculation = factor (user_input);
printf("ld\n", factorial_calculation);
return 0;
}
Your user_input is int but you are passing variable as a float and running your factorial function on it. Factorials are undefined for non-integer nos, so you are better off using int.
In:
printf("ld\n", factorial_calculation);
ld is an invalid format specifer.
In
scanf("%d\n", &user_calculation);
I think you meant
scanf("%d", &user_input);
The following code works:
#include <stdio.h>
int factor (int user_input)
{
if(user_input <=1)
return 1;
else
return (user_input * factor (user_input - 1));
}
int main ()
{
int user_input;
long factorial_calculation;
printf("what factorial number would you like to calculate?\n");
scanf("%d", &user_input);
printf("%d\n",user_input);
factorial_calculation = factor (user_input);
printf("%d\n", factorial_calculation);
return 0;
}
scanf() is notoriously difficult to synchronize with user input. Instead, use fgets() and inspect the string for a number (or numbers if more than one is expected per line).
long factorial_calculation;
char buf [1000];
for (;;)
{
printf("What factorial number would you like to calculate?\n");
if (!fgets (buf, sizeof buf, stdin)) /* probably EOF, hangup, etc.: just exit */
return 0;
if (1 != sscanf(buf, "%ld", &user_calculation))
{
printf ("No number entered, please try again\n");
continue;
}
factorial_calculation = factor (user_input);
}
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}