Using the switch function in C++

Asked

Viewed 273 times

2

The function switch and I don’t know what I’m doing wrong marcos there appear "landmarks and cool" and put murilo "Nice and cool". I’m doing it like this:

#include <stdio.h>
#include <conio.h>
int main(void)
 {
  char marcos;
  printf("Digite um nome e veja? ");
  scanf("%s",&nome);
  switch (nome) 
  { 
    case 'marcos' : 
    printf("Marcos e legal");
    break;
    case 'murilo':
    printf("Murilo e bacana");
    break;
    default: 
    printf("errado");

     getch();
    return 0;
}

  }  
  • Click [Edit], select the code block and press control+K to format, or use the button { } format bar. It would be nice to take advantage of the editing and describe better what went wrong with your attempt.

  • 1

    @Factorals if the cases are numerical cannot be duplicated from this.

  • "switch" is not a function, is a command

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

Unable to use strings in the case, there can only use simple types such as numbers and individual characters (which are no longer numbers). If you need to do it with string have to use if and strcmp() same. In C++ you can use the == in a kind string his own.

You can understand How the switch works behind the scenes?.

And if I were to use string would have to be double quotes ("). Single quotes (') is only for a single character that is not a numerical type, but can be printed as a character. A string is just a sequence of those characters ending with a null (\0).

In addition the variable nome was not declared, was another meaningless that was not used. And it should be declared as array or make dynamic allocation that is very advanced.

And never use conio.h.

Browser other questions tagged

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