ALERT!
Click here to register with a few steps and explore all our cool stuff we have to offer!

Jump to content



Photo

[C] scanf without input


  • Please log in to reply
[C] scanf without input

#1

Mouserox
Mouserox
    Offline
    0
    Rep
    24
    Likes

    Addicted

Posts: 202
Threads: 9
Joined: Oct 07, 2018
Credits: 0

Five years registered
#1

Hello,

I need help with code...

I need to write "ERROR" and return 1 if the user enters nothing.

I tried many things so i think there is a problem with scanf.

 

All code with Polish words:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int sum(const float* tab, unsigned int size, float *result);
int avg(const float* tab, unsigned int size, float *result);

int main()
{	
	float ile;
    float a[10];
    float *tab=a;
    float wynik;
    float *result=&wynik;
    int i=0;
    float podana;
    int size = 0;
    int k=0;
	for(i=0;i<10;i++)
		{
		
 
		printf("Podaj %d liczbe: ",i+1);	
        scanf("%f",&podana);
        
        
        	if(podana==0)
			{
			// KOMUNIKAT WYŚTWIETLONY PRZEZ PROGRAM JEST NIEWŁAŚCIWY; POWINNO BYĆ ERROR
			printf("Zle dane\n");
			return 0;
			}
	
			else
			{
    		*(tab+i)=podana;
			size++;
			k++;	
			}
		}
 
		printf("\nWielkosc tablicy: %d\n",size);
		for(i=0;i<10;i++)
        {
		
    	printf("%f ",* (tab+i))	;
		}
		sum(tab, size, result);
		avg(tab, size, result);
	return 0;
}

int sum(const float* tab, unsigned int size, float *result)
{
	

	int i=0;
	float ile;
	for(i=0;i<10;i++)
		{
	
    	ile+=*(tab+i);
			
		}
	*result= ile;
	printf("\nSuma wynosi: %.2f", *result);
	return 0;
}

int avg(const float* tab, unsigned int size, float *result)
{
	int i=0;
	float ile=0;
	for(i=0;i<10;i++)
		{
	
    	ile+=*(tab+i);
			
		}
	*result= ile/size;
	printf("\nSrednia wynosi: %.2f", *result);
	return 0;
	
}

The code to change:


	        for(i=0;i<10;i++)
		{
		
 
		        printf("input a number");	
                        scanf("%f",&number);
        
        //There should be an if scanf is enter it return 1.
        	        if(number==0)
			{
			printf("Bad input\n");
			return 0;
			}
	

		} 

  • 0

#2

Effervescence
Effervescence
    Offline
    234
    Rep
    801
    Likes

    Veteran

  • PipPipPipPipPipPipPip
Posts: 1265
Threads: 245
Joined: Nov 27, 2017
Credits: 0

Deal with caution
User has an open scam report.
Six years registered
#2
	        for(i=0;i<10;i++)
		{
		
                        number=0;
		        printf("input a number");	
                        scanf("%f",&number);
                        If (number==0)
                              { return 1;}
        //There should be an if scanf is enter it return 1.
        	        if(number==0)
			{
			printf("Bad input\n");
			return 0;
			}
	

		} 

I can think of many better fixes Mouserox


  • 0


 Users browsing this thread: