Language C switch command 2 instructions within the same case

Asked

Viewed 341 times

1

I’m having trouble incrementing using the switch, for example, I want to use an accelerator and every time I call the case '+': it makes two example increments:

potencia=potencia+10;                
altitude=altitude+1000;

One of them, the second is returning incorrect values, I made the code in javascript, works perfectly, now in C am not getting.

Follows code below and image attached.

int main(){

int potencia=0;
int altitude=0;
char acelerador;

do{

    printf("\n +Use (+) para aumentar velocidade/ (-) deminuir:");
    gets(&acelerador);

    switch(acelerador){

    case '+': 
            potencia=potencia+10;
            altitude=altitude+1000;
            printf("\n %d",potencia);
            printf("\n %d",altitude);

 }


 }while(acelerador !='s');

system("PAUSE");
return 0;
}

inserir a descrição da imagem aqui

  • You made a mistake with the throttle variable. Declared as a char (a single character) but is using the gets function to read such a variable, however the gets function reads a string or array of characters and adds the ' 0' terminator. It may be that your reading is destroying the memory area of the variable that is in trouble. We usually close the commands of a case with the break command; otherwise it will continue the execution of the following commands even if they belong to another case.

  • I ran your code smoothly here, the values came out correct. Detail, do not forget to finish one case of switch with break.

  • It really, I circled on another platform and consisted error, I switched to scanf on the char reading and rode quiet. @anonimo

1 answer

0


I recommend not to use gets, in case you want to use fgets instead. However I use scanf even. Exchange gets(&throttle) by:

scanf("%c", &acelerador);

And all will work well.

Complete code with #include and break no case:

#include <stdio.h>
int main(){
  int potencia=0;
  int altitude=0;
  char acelerador;

  do{
    printf("\n +Use (+) para aumentar velocidade/ (-) deminuir:");
    scanf("%c", &acelerador);
    switch(acelerador){
      case '+':
              potencia=potencia+10;
              altitude=altitude+1000;
              printf("\n %d",potencia);
              printf("\n %d",altitude);
              break;
   }
   }while(acelerador !='s');
  system("PAUSE");
  return 0;
}
  • Perfect buddy, perfectly now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.