Taking user input and using a function to check if its valid - c

I'm trying to create a program in which the user enters three integers, and another function checks to see that their input is valid. If the input is not valid, then the user must input three new numbers.
#include <stdio.h>
int sanitizedInput(int a, int b, int c)
{
if(scanf("%d", &a)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &b)==0)
{
printf("Not a number\n");
return 1;
}
else if(scanf("%d", &c) == 0)
{
printf("Not a number\n");
return 1;
}
else
return 0;
}
int main()
{
int a;
int b;
int c;
int check = 1;
do
{
check = 0;
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
check = sanitizedInput(a,b,c);
}while(check);
}
However when I run this code, after entering three valid integers nothing shows up in the terminal and the code only terminates after entering 6 integers. (There are other functions and code in the main function, if that code is necessary to find the problem tell me and I will post it.)

Your code and your writing part is not matching.....
You should check the three numbers are valid or not firstly.
int sanitizedInput(int a, int b, int c)
{
if(a==0 || b==0 || c==0)
{
return 1;
}
else
{
printf("They are valid.....\n");
return 0;
}
}
Then if one of them are invalid, you will be able to take another three input for the returning value of 1. Because while(1) is a true condition.

remove
printf("Enter a number:");
scanf("%d",&a);
printf("Enter a number:");
scanf("%d",&b);
printf("Enter a number:");
scanf("%d",&c);
and stay with check = sanitizedInput(a,b,c);, and add printf("something\n") to the
else
return 0; block
and see what happens

In main() you are taking input for three numbers a,b,c and passing these variables as arguments for sanitizedInput().
Here, instead of checking the variables you are again using scanf() which will take new input.
if(scanf("%d", &a)==0)
The above if condition will not check the value of 'a', it will check the return value of scanf() with '0'.
if statement should be like this
if(a==0)
scanf("%d",&a);
this is same for all three variables.
In main function you are passing variables to sanitizedInput(), there you are checking variables and if not valid you are taking input again, so the variable which you changed are local to that function, which will not reflect in main(). So take care about that.
Hope this will help you.

In your while loop,you actually call scanf twice each variable(a,b,c),so you input number for 6 times.When sanitizedInput(a,b,c) finished,it return 0;so check is 0,the loop is over.I think you can do with in your main:
int main
{
int a;
int b;
int c;
int check = 0;
do
{
check = sanitizedInput(a,b,c);
printf("check = %d\n",check);
}while(!check);
return 0;
}

Related

C Loop until the condition is met problem

I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}

Counting arguments passed to scanf() in C

Is there any way to Count number of arguments passed to scanf() in C ? Specially, while assigning int arrays through scanf().
Example:
int array[1000], i;
for(i=0;i<1000;i++)
scanf("%d",&array[i]);
I need to count how many values are inserted by user
I don't think there's a built in way to do this, but why not just create a counter that increments when scanf returns successfully and break the loop otherwise?
int scanf_counter = 0;
int array[1000], i;
for(i=0;i<1000;i++) {
if(scanf("%d",&array[i] > 0) {
scanf_counter++;
} else {
break;
}
}
Although I'm not sure I understand your question exactly because you could always just find the size of the array by doing this
int size = sizeof(array)/sizeof(array[0])
Look the scanf() fragment carefully, thus:
include
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}

if/else if/else menu issue c

I'm having an issue with my menu. I get a number from the user but whenever I get a number it just does option one no matter what I do. What am I doing wrong?
int main()
{
int array[SIZE];
int size = readNum();
fillArray(array, size);
char option = 'y';
do
{
int num = menu();
if(num == 1)
fillArray(array, size);
else if(num == 2)
{
int newSize = readNum();
fillArray(array, newSize);
}
else
{
sortArray(array);
}
}while(option == 'y');
return 0;
}//end main
int menu()
{
printf("1)Change the values of the array\n2)Change the size of the array and the values in the array\n3)Find and display the mean and median\nChoice: ");
int menuChoice = scanf("%i", &menuChoice);
return menuChoice;
}
The scanf function returns the number or successful conversion it made, not the actual converted value. It seems it always succeeding in reading you value, so will return 1 for one successful conversion.
To return the actual user choice, do not assign to it from the call:
int menuChoice:
scanf("%i", &menuChoice);
return menuChoice;
int menuChoice = scanf("%i", &menuChoice);
scanf returns the number of successful conversions, so if the scan succeeds, you are overwriting the converted value with 1.

error in if condition even i enter code correctly in c programming

#include <stdio.h>
#include <process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i = 0; i < 7; i++)
scanf("%d" ,&enter[i]);
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i = 0; i < 7; i++)
{
if (enter[i]=check)
{
printf("your entry is valid");
exit(0);
}
else if(enter[6]!=check)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
this executes without error but dont work correctly .. always prints out the input is valid.... even i enter the number which is not in array :(
This is assignment, not equality:
if (enter[i]=check)
Change to:
if (enter[i] == check)
Additionally, always check the result of input operations:
if (1 != scanf("%d" ,&enter[i]))
{
/* Handle invalid value. */
}
to ensure subsequent code is operating on variables that have been assigned values.
This line
if (enter[i]=check)
does not do what you expect. You probably meant
if (enter[i]==check)
The assignment is valid C, but instead of checking for equality, it sets enter[i] equal check, and then checks the value of check for being zero. If it is non-zero, the condition succeeds, regardless of the initial value of enter[i]. If the check is zero, then the condition fails, - again, regardless of the initial value of enter[i]. This is a very common mistake; many compilers issue warnings to alert you to the situation.
= is the assignment operator, not equality at all. Doing:
if (enter[i]=check)
enter[i] will take the value check, and then it will check whether enter[i] is nonzero.
if (enter[i] == check)
enter[i]==check)// 2 for compare
proper usage of = is assignment operator whilst == is testing the equality
#include<stdio.h>
#include<process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i=0;i<7;i++)
{
scanf("%d" ,&enter[i]);
}
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i=0;i<7;i++)
{
// printf("\nvalue of i is %d\n" ,i);
if (check==enter[i])
{
printf("your entry is valid");
exit(0);
}
else if(enter[i]!=check && i==6)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
now i got it all right . thanks :)

malloc function is not working properly in C program. the program crashes

I am beginner in C and this is my first program using malloc() function. I think there might be some problem in using this function.I wanted to use an array(cyclelength) where a solution for a range of number(user input) will be put. so the array size depends on user so i used malloc(). but the program is crashing. Here is my code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x,y,num,count,p,k;
for(;;){
printf("enter first integer. must be between 1 and 100000\n");
scanf("%d", &x);
printf("enter second integer. must be between 1 and 100000. must not equal the first integer.\n");
scanf("%d", &y);
if(x>=1 && x<100000 && y>=1 && y<100000 && x!=y){
break;
}
else{
printf("try the whole process again\n");
}
}
if (x<y){
int j;
j=y;
y=x;
x=j;
} //making x always greater than y
int *cyclelength=malloc(5000*sizeof(int));
if (NULL==cyclelength){
printf("process aborted");
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
count=0;
cyclelength[count]=p;
num+=1;
count+=1;
}
free(cyclelength);
cyclelength=NULL;
}
int c=0;
int max=cyclelength[c];
for(;c<x-y;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
printf("%d,%d,%d",x,y,max);
return 0;
}
You're calling free(cyclelength) and then accessing the memory it points to (or, rather, the memory that it pointed to).
(And your error handling could stand some improvement; you print "process aborted", but then continue processing.)
You are using cyclelength after you freed it and set it to NULL:
free(cyclelength);
cyclelength=NULL;
}
int c=0;
int max=cyclelength[c];
for(;c<x-y;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
That's undefined behaviour and likely to crash.
You are using cyclelength after dealloating it so your program is crash.
Try this :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x,y,num,count,p,k;
for(;;){
printf("enter first integer. must be between 1 and 100000\n");
scanf("%d", &x);
printf("enter second integer. must be between 1 and 100000. must not equal the first integer.\n");
scanf("%d", &y);
if(x>=1 && x<100000 && y>=1 && y<100000 && x!=y){
break;
}
else{
printf("try the whole process again\n");
}
}
if (x<y){
int j;
j=y;
y=x;
x=j;
} //making x always greater than y
int *cyclelength=(int *)malloc(5000*sizeof(int));
if (NULL==cyclelength){
printf("process aborted");
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
count=0;
cyclelength[count]=p;
num+=1;
count+=1;
}
// don't assign null to cyclelength
//cyclelength=NULL;
}
int c=0;
int max=cyclelength[c];
for(;c<x-y;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
printf("%d,%d,%d",x,y,max);
// free here
free(cyclelength);
return 0;
}

Resources