In this article, we slightly modify the format of the study topics. At the beginning, let's look at an example with statement switch(switch), which will be a lot of comments about how, that occurs in the code. A whole theory will be located below.
The work of the statement of multiple choiceswitch in C ++, we consider in addressing this problem: Let's, the user has a numbered list of the metro stations in Barcelona. You must write code, wherein the dialogue with the user is implemented, namely, asked to enter room underground station. After entering the Station Number, we have to show it on the screen and the name of the travel time. If, however, with the number of stations is not, inform and propose to enter the number again. Begin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); int answer = 0; // будет хранить выбор пользователя bool var = true; // управляющая переменная цикла do while cout << "Введите номер станции метро, для расчета времени в пути (от 1 до 5): "; do{ cin >> answer; // ввод значения switch (answer) // switch принимает переменную answer и ищет подходящий case { case 1: // если answer равно 1, на экран выйдут сообщения этого case cout << "Станция метро Trinitat Nova: "; cout << "Время в пути - 15 мин." << endl; break; // выход из switch. иначе будет переход case(2) и т.д. case 2: // если answer равно 2 cout << "Станция метро Casa de l’Aigua: "; cout << "Время в пути - 19 мин." << endl; break; case 3: cout << "Станция метро Torre Baro Vallbona: "; cout << "Время в пути - 25 мин." << endl; break; case 4: cout << "Станция метро Ciutat Meridiana: "; cout << "Время в пути - 30 мин." << endl; break; case 5: cout << "Станция метро Can Cuias: "; cout << "Время в пути - 38 мин." << endl; break; default: // если ни один case не сработал, сработает default cout << "Станции под номером " << answer << " нет! "; cout << "Сделайте правильный выбор (от 1 до 5): "; } // если введено правильное значение (от 1 до 5) // default не сработает и выполнится блок if // переменная var примет значение false // и цикл do while не повторится if (answer >= 1 && answer <= 5) var = false; } while (var); //цикл повторится, пока var не изменит значение на false return 0; } |
To string 13 – everything is clear: Ads necessary variables, conclusions Questions on the screen, and entry into the loop do while. In string 14 we got valueanswer, which introduces the user. Then look, how interesting works switch() : in parentheses pass him answer (string 16) and next to each wordcase write possible valuesanswer, the user can enter (1, 2, 3 …).
after each case you see the statement : , he required. It is followed by the command, that must be met, if the valuecase coincides with the value of answer. Statementbreak at the end of each block case It is also required. It indicates to the compiler, if this case It was performed, you have to get out of switch(). That is actually, when performed switch () begins search and search for the desired case.
Ifanswer equal to 1, work case 1 and the screen will show the, that it is registered to a keywordbreak, and all other case, будут проигнорированы. Если answer equal to 2 – executed onlycase 2 and exited switch(). What if no value blocks case does not match, with the value, that took switch() (in our case answer)? For this purpose the blockdefault. Before him it comes, just then, when none of case not worked and, respectively, not fulfilled nonebreak these units.
In our example,, it will work if the value, which will bring the user, will be <1 or >5. Then the user will see on the screen a message that, that with such a number of subway stations, and there is no need to re-enter.
In the loop, we always check the valueanswer, which is entered by the user. This is done using if . If the value is within a suitable range, we (from 1 to 5 ), the manipulated variable var It will be set 0. In this case, the user will no longer be prompted to enter a new value.
Here's how the program works:
What you should remember:
- syntax:
- blockdefault It can be positioned anywhere in the blockswitch() For example the first and second case . His code in any event will run only, if you find the value in the blocks case. But, I suggest you have it at the end, as do most programmers. It is an unwritten rule.
- a lower block switch(), whetherdefault or case, operator break You can not specify. This is done in this example. But we should remember, that in all other break mandatory!
- default It is optional. His in switch() may not be at all. In this case, If no value blocks case does not coincide with the, that took switch() , the program moves to the next line of code, located under the switch()
- sometimes blocks case check character, instead of numerical values. Then you must take these characters in single quotes – case ‘b’: , case ‘G’: , case ‘+’ etc.
Anyone who has a desire to – see video tutorial on the topic.
Still have questions – ask them in the comments. Be sure to answer all. Learn the basics of programming with us! More examples usingswitch in C ++ discussed in the article Tasks: The switch statement in the C++.
#include
#include
using namespace std;
int main()
{
setlocale(LC_ALL, “RU”);
int answer;
cout << "\a \a\a";
cout << " \t How are user?" <> answer;
switch (answer)
{
case (“fine”):
case (“well”) :
case (“Good”) :
case (“Fine”) :
case (“excellent”) :
case(“Otilichno”) :
break;
cout << "Ок тогда начинаем" << endl;
case ("не очень"):
case ( "плохо:пойдет") :
case ("не спрашивай") :
case ( "Не очень" ):
case ("Плохо пойдет" ):
case ( "Не спрашивай") :
cout << "Ок тогда в другой раз заходи" << endl;
break;
default:
cout << "Пожалуйста граматно пиши" << endl;
}
system("pause");
return 0;
}
somebody help me
you want to push the string into int?
This lesson is in the thread “Loops and branching statements” under number 3. This program uses do and while statements which are only covered in #6. In short, I'd rather swap them or something., I haven't looked further, but I don't understand how these operators work in this program.
help me please, I'm a beginner.
float AddVat(float price, int category)
float total_price=0;
The goal is for the function to calculate and return the total cost including tax (not allowed to use scanf, switch only)
taxes:
1 category 20%
2- 20%
3-20%
4-15%
5-8%
6-0%
It is not clear how case: checks the value of the variable int answer = 0 replacing it
more if else logic
Why do do while here????
It works without it, and cin can be placed behind the loop and everything will work the same