V
V
Vyacheslav2015-02-08 19:13:42
C++ / C#
Vyacheslav, 2015-02-08 19:13:42

Why does the loop (C language) work incorrectly?

#include<stdio.h>
main()
{
  /*4.28*/
  int earnings, wagesperunit, wages, hourly, hours, cod, i, numberofunits;
  for(i=1;i<=5;i++){
    printf("Enter the cod of worker: ");
    cod=getchar();
    switch(cod){
        case '1':
        printf("Enter the wages for administrator: ");
        scanf("%d",&wages);
        printf("Wages is: %d\n",wages);
        break;

        case '2':
        printf("Enter the business hours: ");
        scanf("%d",&hours);
        printf("Enter the hourly: ");
        scanf("%d",&hourly);
        hourly=hourly*40;
        if(hours>=40)
          hourly=hourly+((hours-40)*1.5);
        printf("Wages is: %d\n",hourly);
        break;

        case '3':
        printf("Enter the earnings: ");
        scanf("%d",&earnings);
        earnings=earnings*0.057+250;
        printf("Wages is: %d\n", earnings);
        break;

        case '4':
        printf("Enter wages per unit: ");
        scanf("%d", &wagesperunit);
        printf("Enter number of units: ");
        scanf("%d", &numberofunits);
        wagesperunit=wagesperunit*numberofunits;
        printf("Wages is: %d\n", wagesperunit);
        break;

        case '\n': case ' ':
        break;

        default:
          printf("Incorrect letter cod. Enter a new cod.\n");
          break;
      }
  }

return 0;
}

This common exercise from Deitel's book "How to Program in C++" got me into a dead end. The iteration is somehow wrong in the loop. However, here is a screenshot of the console program.
6fc6d8db766f446ba26789ceca8b73de.bmp
I don’t know why, but after the first input of a value, the program starts to display messages twice asking you to enter values.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2015-02-08
@gbg

An extra 'Enter' remains in the buffer, then it works

case '\n': case ' ':
        break;
and you find yourself again at the invitation to enter the code.
You can make sure by adding some message before the break in this case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question