asked    Louis     2018-10-22       c       77 view        4 Answers

[SOLVED] Output not shown correctly

I am a beginner in C programming and I have written the following code but it is producing an error at the output. The code is-:

#include <stdio.h>
#include <conio.h>

void main()
{
  int n=0;
  int i,k;
  char name;
  printf("\t\t Program to find the overtime of 10 workers\n\n");
  for(i=0;i<=10;i++){
    printf("Enter the name of worker");
    scanf("%char",&name);
    printf("Enter the number of hours worked");
    scanf("%d",&n);
    if(n>10){
      k=n-10;
      printf("He is eligible for overtime for overtime of rs %d\n",k*12); 
    }
    else{
      k=0;
      printf("He is not eligible to any overtime in rs %d \n",k);
    }
  }
  getchar();
}

It is showing correct result for the first time but when I entered the name of the worker second time it is giving me the wrong output.I am unable to detect the mistake.

  4 Answers  

        answered    Booth     2018-10-22      

  1. name should be char array ==> char name[15];
  2. The second visible error is the for loop: When you are looking for 10 worker entries, your array loop is running from i=0 to i=10 which would be 11 entries. So, for(i=0;i<10;i++) ==> i<10 instead of i<=10.
  3. your scanf statement ==> scanf("%s",name); not a %char which is wrong.


        answered    Peter     2018-10-22      

Your code has several problems:

  • conio.h header is useless,
  • You do not reserve enough space to store a name,
  • you do not check for scanf result.

Corrected, your code could looks like:

/* only include stdio.h, conio.h is not portable and unnecessary here */
#include <stdio.h>

/* main should return an int*/
int main(void)
{
    int n=0;
    int i,k;
    /* often, a name is composed of several characters */
    char name[128];
    printf("\t\t Program to find the overtime of 10 workers\n\n");
    for( i=0; i<10; i++){
        printf("Enter the name of worker\n");

        if (1 != scanf("%s", name))
        {
            /* on error, exit loop */
            perror("scanf");
            break;
        }

        printf("Enter the number of hours worked\n");
        if (1 != scanf("%d",&n))
        {
            /* scanf did not manage to read one integer, exit loop */
            perror("scanf");
            break;
        }
        if (n>10) {
            k=n-10;
            printf("%s is eligible for overtime for overtime of rs %d\n", name, k*12); 

        }
        else{
            printf("%s is not eligible to any overtime in rs 0 \n",name);
        }
    }
    getchar();

    return 0;
}

And to finish, here: a good reading about scanf:



        answered    Len     2018-10-22      

There are few problems in your code. Firstly this

scanf("%char",&name);

is wrong, instead of %char you should provide the correct format specifier to scan the name. This

char name;
scanf("%c",&name);

runs successfully but I hope you don't want a person name in single character, so better declare name as array of char. For e.g

char name[MAX_LEN];/*define MAX_LEN] */

and then use

scanf("%s",name);

And the for loop condition i<=10 rotates the loop 11 times not 10 times(as you mentioned 10 worker), probably you want i<10.

Also instead of void main() { } use

int main(void) {

    return 0;
}

Edit :- Since you modify the question. And It is showing correct result for the first time but when I entered the name of the worker second time it is giving me the wrong output.I am unable to detect the mistake. ?

To avoid this

scanf("%c",&c);

should be

scanf(" %c",&c); /* give the white space before %c */

Side note, it's highly recommended to check the return value of predefined function like scanf() to know whether they got succeed or failed , for that read the manual page. For e.g

char name;
int ret = scanf(" %c",&name);
if(ret == 1) {
    /* do something */
}
else {
   /* error handling */
}


        answered    Hayden     2018-10-22      

This is due to format specifier %char. It is not a valid format specifier, there is no such thing as %char that C understands.

Make a habit of standard library reading man pages of the functions that you are planning to use. For example, scanf. Read through Conversions section of that man page. That will guide you about what format specifiers are to be used with scanf().

Look at the variable there:

char name;

Its a char, it can only hold one character. To store a name, I assume that you need more than one char. So you might want to use an array of characters.

So, change it to:

char name[MAX_LENGTH_NAME];  //MAX_LENGTH_NAME can be a macro set to some 

value, example 32?

And change your scanf() call for worker name to,

scanf("%s", name);   // Note: `&` is gone here!

Getting the return values from scanf(), and adding some error handling for unexpected return will save you a lot of pain going ahead.

The printf() says, its a program to calculate something for 10 workers,

for(i=0;i<=10;i++)

This loops for 11 iterations, not 10. I hope you aren't the 11th worker :-).
Change it to for(i = 0; i < 10; i++).

Additionally, conio.h is non-standard. If you are developing on a platform that mandates you using this header, you may want consider switching to a better development environment. For example, a linux machine with a bash terminal and a standard gcc compiler.

Lastly, void main is bad, use int main(void) instead. To know more on why, read What should main() return?

Irrelevant: GUI Design and what messages you throw up on console are very crucial going ahead. He is strictly masculine :D Aren't there any women workers around? It could be way better if you start printing the name instead of He.





Your Answer





 2018-10-22         Dennis

How to return data from inside promise.all

findCustomerOrders(customerId) { return APIService.getCustomerOrders(this, customerId) .then((data) => { data.map(order => { return Promise.all([APIService.getShippingAddress(this, order.id), APIService.getProducts(this,order.id), APIService.getCustomerById(this, customerId)]) .then((returnedData)=>{ return buildOrder(returnedData); }); }); }); }The function where the data is to be returned isfindCustomerOrders(1).then((final) =>{console.log(final)});I have to return the data which is returned by buil...
 node.js                     4 answers                     55 view
 2018-10-22         Annabelle

how to store and validate qr code in server using nodejs and mongoose

We are implementing a mobile app using the following technologies:Node.JS & express MongoDB & mongooseFlutterSuppose we should generate QR Code with the goods information like name, price, expiration date and etc. which should be unique and whenever customer scan the QR Code it should be validated by connecting to the server, fetching data and add the selected good to cart.As I have searched on the internet, I found that we should convert the data to canvas (to have QR Code). Is there any solution to generate QR code in server side, store and validate it in mongodb?...
 node.js                     1 answers                     57 view
 2018-10-22         Yehudi

Adding Load Balancer Rule via Powershell

I'm attempting to add a load balancer rule via Powershell as we need to open multiple ports for passive ftp.Connect-AzureRmAccountSet-AzureRmContext -SubscriptionId "MySubId"$slb = Get-AzureRmLoadBalancer -Name "MyLB" -ResourceGroupName "MyRG"$prb = Get-AzureRmLoadBalancerProbeConfig -Name "MyProbe" -LoadBalancer $slb$beaddpool = Get-AzureRmLoadBalancerBackendAddressPoolConfig -Name "BEADDPOOL" -LoadBalancer $slb$slb | Add-AzureRmLoadBalancerRuleConfig -Name "PassivePort_50010" -FrontendIPConfiguration $slb.FrontendIpConfigurations[0] -BackendAddressPool $beaddpool -Protoco...
 azure                     2 answers                     60 view