Can't get my do-while loop to work

0 Elias Zaguri · September 15, 2015
So i wrote a simple code. User writes a number between 0-5 and the program answer in morsecode. After it's done you get a question if u want to run the program again, and here is where i get the problem. Instead of starting again, the program only writes " number between 0-5 : invalid number" until you close it. I want it to start over from the beggining.

Help please and sorry or my English



#include <stdio.h>
#include <stdlib.h>
/* user writes a number, program answers in morsecode*/

int main()
{

int choice;

do

{




  char number;
  printf("number between 0-5: ");
  scanf("%c", &number);


  switch (number)
 {
    case '0' :
    printf("morsecode:-----\n");
    break;

    case '1' :
    printf("morsecode:.----\n");
    break;

    case '2' :
        printf("morsecode: .. ---\n");
        break;
    case '3' :
        printf("morsecode:...--\n");
        break;
    case '4' :
        printf("morsecode:....-\n");
        break;
    case '5' :
        printf("morsecode:.....\n");
        break;
    default :
    printf("invalid number \n");

 }

    printf("do you want to continue? (1 for yes 0 for no: )");
   scanf("%d", &choice);
}

while (choice !=0);

     return 0;
 }





Post a Reply

Replies

Oldest  Newest  Rating
0 Jon Z. · September 17, 2015
you are using a char and sometimes treating it as a char, and sometime as an int...
0 Sandra T · September 16, 2015
You're welcome! :)
0 Elias Zaguri · September 16, 2015
Thank you very much for the help! appriciate it :)
0 Sandra T · September 15, 2015
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main()
{
 int choice;
 char number;

 printf("number between 0-5: ");
 scanf("   %c", &number);

do

{
switch (number)
{
case '0' :
printf("morsecode:-----\n");
break;

case '1' :
printf("morsecode:.----\n");
break;

case '2' :
printf("morsecode: .. ---\n");
break;
case '3' :
printf("morsecode:...--\n");
break;
case '4' :
printf("morsecode:....-\n");
break;
case '5' :
printf("morsecode:.....\n");
break;
default :
printf("invalid number \n");

}

printf("do you want to continue? (1 for yes 0 for no: )");
scanf("   %d", &choice);
if (choice==1) {
    printf("number between 0-5: ");
    scanf("   %c", &number);
}


}

while (choice !=0);
      return 0;

}
I'VE MADE  SOME CHANGES AND IT WORKS. 
ADVICE:  WHEN YOU SCANF OR PRINTF  STH.  LEAVE A SPACE BEFORE   %c, %d, %s, %f...
  • 1

C

126,472 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator