Create a console figurer in C++

The usual starting indicate for a C++ developer is a "Hi, earth!" awarding that runs on the command line. That's what you'll create first in Visual Studio in this article, and then we'll motility on to something more challenging: a calculator app.

Prerequisites

  • Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. If it'south non installed yet, meet Install C++ support in Visual Studio.

Create your app projection

Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. A project contains all the options, configurations, and rules used to build your apps. It besides manages the human relationship between all the project'due south files and any external files. To create your app, commencement, y'all'll create a new project and solution.

  1. If yous've just started Visual Studio, you'll run across the Visual Studio Start dialog box. Choose Create a new project to become started.

    Screenshot of the Visual Studio 2022 initial dialog.

    Otherwise, on the menubar in Visual Studio, choose File > New > Projection. The Create a new projection window opens.

  2. In the list of project templates, choose Console App, and then cull Side by side.

    Screenshot of choosing the Console App template.

    Important

    Make sure yous cull the C++ version of the Console App template. It has the C++, Windows, and Console tags, and the icon has "++" in the corner.

  3. In the Configure your new project dialog box, select the Projection name edit box, name your new projection CalculatorTutorial, so choose Create.

    Name your project in the Configure your new project dialog.

    An empty C++ Windows console awarding gets created. Console applications employ a Windows panel window to display output and accept user input. In Visual Studio, an editor window opens and shows the generated code:

                        // CalculatorTutorial.cpp : This file contains the 'main' office. Program execution begins and ends in that location. //  #include <iostream>  int chief() {     std::cout << "Hi Earth!\north"; }  // Run programme: Ctrl + F5 or Debug > Start Without Debugging menu // Debug programme: F5 or Debug > Get-go Debugging menu  // Tips for Getting Started: //   1. Utilize the Solution Explorer window to add/manage files //   2. Use the Team Explorer window to connect to source control //   3. Use the Output window to come across build output and other messages //   4. Use the Error List window to view errors //   v. Become to Project > Add New Detail to create new code files, or Project > Add Existing Item to add existing code files to the project //   half dozen. In the future, to open this projection again, go to File > Open > Project and select the .sln file                                      

Verify that your new app builds and runs

The template for a new Windows console awarding creates a elementary C++ "Hi Earth" app. At this point, yous tin see how Visual Studio builds and runs the apps you create correct from the IDE.

  1. To build your project, choose Build Solution from the Build menu. The Output window shows the results of the build process.

    Screenshot of Visual Studio 2019 with the Output window showing the result of the build process.

  2. To run the code, on the menu bar, cull Debug, Starting time without debugging.

    Screenshot of the Visual Studio 2019 Microsoft Visual Studio Debug Console showing the code ran successfully.

    A console window opens and so runs your app. When you first a panel app in Visual Studio, it runs your code, and then prints "Press whatever key to close this window . . ." to give you a chance to run across the output. Congratulations! You lot've created your first "Hello, world!" console app in Visual Studio!

  3. Press a key to dismiss the console window and return to Visual Studio.

You now have the tools to build and run your app after every modify, to verify that the code still works as you expect. Later, we'll bear witness you how to debug it if it doesn't.

Edit the code

Now permit's plow the code in this template into a calculator app.

  1. In the CalculatorTutorial.cpp file, edit the code to match this example:

                        // CalculatorTutorial.cpp : This file contains the 'chief' office. Program execution begins and ends there. //  #include <iostream>  using namespace std;  int master() {     cout << "Calculator Console Application" << endl << endl;     cout << "Please enter the functioning to perform. Format: a+b | a-b | a*b | a/b"         << endl;     return 0; }  // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Kickoff Debugging menu // Tips for Getting Started: //   i. Use the Solution Explorer window to add/manage files //   2. Utilize the Team Explorer window to connect to source command //   3. Employ the Output window to see build output and other messages //   iv. Utilize the Error List window to view errors //   five. Go to Project > Add together New Item to create new code files, or Projection > Add Existing Item to add existing code files to the projection //   6. In the futurity, to open this project once more, become to File > Open > Project and select the .sln file                                      

    Understanding the code:

    • The #include statements allow you to reference code located in other files. Sometimes, you may meet a filename surrounded by angle brackets (<>); other times, it'southward surrounded by quotes (" "). In general, angle brackets are used when referencing the C++ Standard Library, while quotes are used for other files.
    • The using namespace std; line tells the compiler to wait stuff from the C++ Standard Library to be used in this file. Without this line, each keyword from the library would have to be preceded with a std::, to denote its telescopic. For example, without that line, each reference to cout would have to exist written as std::cout. The using argument is added to make the code expect more clean.
    • The cout keyword is used to print to standard output in C++. The << operator tells the compiler to ship whatever is to the right of it to the standard output.
    • The endl keyword is like the Enter fundamental; it ends the line and moves the cursor to the next line. It is a better practice to put a \north inside the string (contained by "") to practice the aforementioned affair, as endl ever flushes the buffer and can hurt the functioning of the program, but since this is a very small app, endl is used instead for better readability.
    • All C++ statements must end with semicolons and all C++ applications must contain a master() function. This office is what the program runs at the start. All code must be accessible from main() in order to exist used.
  2. To save the file, enter Ctrl+S, or choose the Salvage icon near the elevation of the IDE, the floppy disk icon in the toolbar under the menu bar.

  3. To run the application, printing Ctrl+F5 or go to the Debug menu and choose Showtime Without Debugging. You should see a panel window appear that displays the text specified in the code.

  4. Close the console window when you lot're done.

Add lawmaking to practise some math

It's time to add some math logic.

To add a Calculator class

  1. Go to the Project menu and choose Add Class. In the Class Proper name edit box, enter Calculator. Cull OK. Two new files get added to your project. To save all your changed files at in one case, press Ctrl+Shift+Southward. It's a keyboard shortcut for File > Salve All. There'south also a toolbar push for Salvage All, an icon of two floppy disks, constitute beside the Save push. In general, it'due south good exercise to exercise Relieve All frequently, and then you lot don't miss any files when you salve.

    Screenshot of the Add Class dialog box with Calculator typed in the Class Name text box.

    A class is similar a pattern for an object that does something. In this example, we define a calculator and how it should piece of work. The Add Grade wizard you used above created .h and .cpp files that have the aforementioned proper name equally the class. Yous tin see a full list of your project files in the Solution Explorer window, visible on the side of the IDE. If the window isn't visible, yous tin can open it from the menu bar: choose View > Solution Explorer.

    Screenshot of the Visual Studio 2019 Solution Explorer window displaying the Calculator Tutorial project.

    You should now have three tabs open up in the editor: CalculatorTutorial.cpp, Reckoner.h, and Calculator.cpp. If you accidentally shut ane of them, yous can reopen it past double-clicking it in the Solution Explorer window.

  2. In Calculator.h, remove the Computer(); and ~Calculator(); lines that were generated, since you won't need them here. Next, add the post-obit line of code so the file now looks like this:

                        #pragma once grade Calculator { public:     double Calculate(double x, char oper, double y); };                                      

    Agreement the code

    • The line you added declares a new function chosen Calculate, which we'll use to run math operations for addition, subtraction, multiplication, and segmentation.
    • C++ code is organized into header (.h) files and source (.cpp) files. Several other file extensions are supported by diverse compilers, but these are the master ones to know about. Functions and variables are unremarkably declared, that is, given a proper noun and a blazon, in header files, and implemented, or given a definition, in source files. To access lawmaking divers in another file, you can use #include "filename.h", where 'filename.h' is the proper noun of the file that declares the variables or functions you desire to apply.
    • The ii lines you deleted declared a constructor and destructor for the form. For a simple class like this 1, the compiler creates them for you, and their uses are beyond the scope of this tutorial.
    • It's practiced exercise to organize your code into dissimilar files based on what it does, then it's easy to find the code you lot need later on. In our case, we define the Calculator class separately from the file containing the main() function, just nosotros programme to reference the Calculator class in main().
  3. You'll see a green squiggle appear nether Calculate. It's because nosotros haven't defined the Calculate function in the .cpp file. Hover over the word, click the lightbulb (in this instance, a screwdriver) that pops up, and choose Create definition of 'Summate' in Estimator.cpp.

    Screenshot of Visual Studio 2019 showing the Create definition of Calculate in Calculator C P P option highlighted.

    A pop-up appears that gives you a peek of the code change that was fabricated in the other file. The code was added to Reckoner.cpp.

    Pop-up with definition of Calculate.

    Currently, information technology only returns 0.0. Permit's change that. Press Esc to close the pop-upwardly.

  4. Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and ~Calculator() sections (as you did in the .h file) and add together the following code to Calculate():

                        #include "Estimator.h"  double Estimator::Calculate(double x, char oper, double y) {     switch(oper)     {         example '+':             render 10 + y;         case '-':             render x - y;         case '*':             return x * y;         case '/':             render x / y;         default:             render 0.0;     } }                                      

    Understanding the lawmaking

    • The office Summate consumes a number, an operator, and a 2d number, then performs the requested operation on the numbers.
    • The switch statement checks which operator was provided, and but executes the case respective to that operation. The default: instance is a fallback in case the user types an operator that isn't accepted, and so the program doesn't suspension. In full general, it's best to handle invalid user input in a more elegant way, only this is beyond the scope of this tutorial.
    • The double keyword denotes a blazon of number that supports decimals. This style, the calculator tin can handle both decimal math and integer math. The Summate function is required to always render such a number due to the double at the very first of the lawmaking (this denotes the function'due south return type), which is why nosotros return 0.0 even in the default case.
    • The .h file declares the part prototype, which tells the compiler upfront what parameters information technology requires, and what return type to expect from information technology. The .cpp file has all the implementation details of the function.

If you build and run the code again at this bespeak, information technology volition yet get out after request which operation to perform. Side by side, you'll modify the main function to do some calculations.

To call the Calculator class member functions

  1. Now allow's update the main function in CalculatorTutorial.cpp:

                        // CalculatorTutorial.cpp : This file contains the 'main' role. Program execution begins and ends there. //  #include <iostream> #include "Calculator.h"  using namespace std;  int main() {     double x = 0.0;     double y = 0.0;     double result = 0.0;     char oper = '+';      cout << "Calculator Console Application" << endl << endl;     cout << "Please enter the functioning to perform. Format: a+b | a-b | a*b | a/b"          << endl;      Estimator c;     while (true)     {         cin >> x >> oper >> y;         issue = c.Summate(x, oper, y);         cout << "Result is: " << result << endl;     }      return 0; }                                      

    Understanding the code

    • Since C++ programs e'er start at the main() function, nosotros need to call our other code from in that location, so a #include statement is needed.
    • Some initial variables x, y, oper, and outcome are alleged to store the kickoff number, second number, operator, and final result, respectively. It is always good practice to give them some initial values to avoid undefined beliefs, which is what is done here.
    • The Reckoner c; line declares an object named 'c' every bit an instance of the Calculator course. The form itself is just a blueprint for how calculators work; the object is the specific reckoner that does the math.
    • The while (true) statement is a loop. The code inside the loop continues to execute over and over again every bit long every bit the status within the () holds true. Since the condition is simply listed as truthful , it'southward always true, and then the loop runs forever. To close the programme, the user must manually close the panel window. Otherwise, the program ever waits for new input.
    • The cin keyword is used to accept input from the user. This input stream is smart plenty to process a line of text entered in the console window and place it inside each of the variables listed, in gild, bold the user input matches the required specification. Y'all can alter this line to take dissimilar types of input, for instance, more than two numbers, though the Calculate() office would also need to be updated to handle this.
    • The c.Summate(10, oper, y); expression calls the Summate function defined earlier, and supplies the entered input values. The function then returns a number that gets stored in result.
    • Finally, result is printed to the console, so the user sees the result of the adding.

Build and test the code over again

At present it's fourth dimension to test the program once again to make sure everything works properly.

  1. Press Ctrl+F5 to rebuild and kickoff the app.

  2. Enter 5 + 5, and press Enter. Verify that the result is ten.

    Screenshot of the Visual Studio 2019 Microsoft Visual Studio Debug Console showing the correct result of 5 + 5.

Debug the app

Since the user is gratis to blazon anything into the console window, let's brand sure the reckoner handles some input equally expected. Instead of running the plan, allow's debug it instead, then we tin can inspect what it's doing in detail, step-by-step.

To run the app in the debugger

  1. Fix a breakpoint on the result = c.Calculate(ten, oper, y); line, but later the user was asked for input. To ready the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. A red dot appears.

    Screenshot of Visual Studio 2019 showing the red dot that represents a breakpoint.

    Now when we debug the program, it always pauses execution at that line. Nosotros already have a crude idea that the program works for simple cases. Since nosotros don't want to pause execution every time, permit's make the breakpoint conditional.

  2. Right-click the reddish dot that represents the breakpoint, and choose Weather condition. In the edit box for the status, enter (y == 0) && (oper == '/'). Choose the Close button when you're done. The condition is saved automatically.

    Screenshot of Visual Studio 2019 showing the Breakpoint Settings section and a condition added to the Is true value.

    At present we suspension execution at the breakpoint specifically if a division by 0 is attempted.

  3. To debug the program, press F5, or cull the Local Windows Debugger toolbar push that has the light-green arrow icon. In your console app, if you lot enter something similar "5 - 0", the program behaves normally and keeps running. All the same, if you type "10 / 0", it pauses at the breakpoint. You tin even put whatsoever number of spaces betwixt the operator and numbers: cin is smart plenty to parse the input appropriately.

    Screenshot of Visual Studios 2019 showing that the program paused at the conditional breakpoint.

Useful windows in the debugger

Whenever you debug your code, you may notice that some new windows announced. These windows can assist your debugging experience. Accept a look at the Autos window. The Autos window shows you the current values of variables used at to the lowest degree three lines before and up to the current line. To see all of the variables from that function, switch to the Locals window. Y'all can really alter the values of these variables while debugging, to see what effect they would take on the programme. In this example, we'll leave them lonely.

Screenshot of the Locals window in Visual Studio 2019.

You can besides just hover over variables in the code itself to see their current values where the execution is currently paused. Brand sure the editor window is in focus by clicking on it get-go.

Screenshot of Visual Studio 2019 showing the tooltip that appears displaying the value of the variable.

To continue debugging

  1. The yellow line on the left shows the current point of execution. The current line calls Calculate, so press F11 to Stride Into the role. Yous'll discover yourself in the body of the Calculate function. Be careful with Step Into; if you do it also much, you may waste product a lot of fourth dimension. It goes into whatever code you use on the line you lot are on, including standard library functions.

  2. Now that the point of execution is at the start of the Calculate part, press F10 to movement to the next line in the programme'southward execution. F10 is also known every bit Stride Over. Y'all can utilise Step Over to move from line to line, without delving into the details of what is occurring in each role of the line. In general you should use Footstep Over instead of Step Into, unless you want to dive more deeply into code that is beingness called from elsewhere (every bit y'all did to reach the trunk of Calculate).

  3. Proceed using F10 to Step Over each line until you get back to the main() office in the other file, and stop on the cout line.

    It looks similar the program is doing what is expected: it takes the first number, and divides information technology by the 2nd. On the cout line, hover over the result variable or have a look at result in the Autos window. You lot'll see its value is listed as "inf", which doesn't expect correct, so allow's gear up it. The cout line just outputs whatever value is stored in result, so when you step one more line forward using F10, the console window displays:

    Screenshot of the Visual Studio 2019 Microsoft Visual Studio Debug Console showing the result of dividing by zero.

    This issue happens because division by nothing is undefined, so the program doesn't have a numerical reply to the requested operation.

To prepare the "divide past zippo" fault

Permit'southward handle partitioning by zero more than gracefully, so a user tin empathize the problem.

  1. Brand the following changes in CalculatorTutorial.cpp. (Y'all can leave the program running every bit yous edit, thank you to a debugger feature called Edit and Keep):

                        // CalculatorTutorial.cpp : This file contains the 'master' function. Programme execution begins and ends there. //  #include <iostream> #include "Reckoner.h"  using namespace std;  int main() {     double x = 0.0;     double y = 0.0;     double effect = 0.0;     char oper = '+';      cout << "Calculator Console Application" << endl << endl;     cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b" << endl;      Calculator c;     while (truthful)     {         cin  >> x  >> oper  >> y;         if (oper == '/' && y == 0)         {             cout << "Segmentation by 0 exception" << endl;             continue;         }         else         {             result = c.Calculate(ten, oper, y);         }         cout << "Result is: " << outcome << endl;     }      return 0; }                                      
  2. Now press F5 one time. Programme execution continues all the way until it has to pause to ask for user input. Enter 10 / 0 again. Now, a more than helpful bulletin is printed. The user is asked for more input, and the program continues executing commonly.

    Screenshot of the Visual Studio 2019 Microsoft Visual Studio Debug Console showing the final result after changes.

    Note

    When you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the debugger is still running your sometime code, and has not nonetheless updated information technology with your changes. The debugger pops upward a dialog to inform you when this happens. Sometimes, you may demand to printing F5 to refresh the code being executed. In particular, if you brand a modify inside a office while the betoken of execution is inside that function, you lot'll demand to step out of the function, and so back into information technology again to go the updated code. If that doesn't work for some reason and you encounter an mistake bulletin, you can stop debugging past clicking on the red square in the toolbar under the menus at the meridian of the IDE, then showtime debugging again by entering F5 or by choosing the dark-green "play" arrow beside the stop button on the toolbar.

    Agreement the Run and Debug shortcuts

    • F5 (or Debug > Start Debugging) starts a debugging session if one isn't already active, and runs the program until a breakpoint is hit or the program needs user input. If no user input is needed and no breakpoint is available to striking, the program terminates and the console window closes itself when the program finishes running. If you accept something like a "Hello Earth" program to run, utilize Ctrl+F5 or set a breakpoint earlier you enter F5 to go on the window open up.
    • Ctrl+F5 (or Debug > Kickoff Without Debugging) runs the application without going into debug style. This is slightly faster than debugging, and the console window stays open later the plan finishes executing.
    • F10 (known equally Step Over) lets yous iterate through lawmaking, line-by-line, and visualize how the code is run and what variable values are at each step of execution.
    • F11 (known as Step Into) works similarly to Step Over, except it steps into any functions called on the line of execution. For example, if the line being executed calls a role, pressing F11 moves the pointer into the body of the function, so y'all can follow the part's lawmaking being run before coming back to the line yous started at. Pressing F10 steps over the function call and just moves to the next line; the office call still happens, but the plan doesn't pause to bear witness y'all what it'southward doing.

Close the app

  • If information technology's even so running, shut the console window for the reckoner app.

Add Git source control

At present that yous've created an app, you might want to add information technology to a Git repository. We've got you covered. Visual Studio makes that process easy with Git tools you lot can use directly from the IDE.

Tip

Git is the almost widely used modern version control system, and so whether you're a professional developer or you're learning how to code, Git tin be very useful. If you're new to Git, the https://git-scm.com/ website is a skilful identify to start. There, you can find crook sheets, a popular online book, and Git Basics videos.

To associate your lawmaking with Git, y'all offset past creating a new Git repository where your lawmaking is located. Here's how:

  1. In the status bar at the lesser-correct corner of Visual Studio, select Add to Source Control, and so select Git.

    Screenshot of the Git source control buttons below the Solution Explorer pane, with the Add to Source Control button highlighted.

  2. In the Create a Git repository dialog box, sign in to GitHub.

    Screenshot of the Create a Git Repository dialog window where you can sign in to GitHub.

    The repository name automobile-populates based on your folder location. By default, your new repository is private, which ways you're the only 1 who can access it.

    Tip

    Whether your repository is public or private, information technology's all-time to have a remote fill-in of your code stored deeply on GitHub. Even if yous aren't working with a squad, a remote repository makes your code bachelor to you from any computer.

  3. Select Create and Push.

    After yous create your repository, you see status details in the status bar.

    Screenshot of the repo status bar that's below the Solution Explorer pane in Visual Studio.

    The first icon with the arrows shows how many outgoing/incoming commits are in your current branch. Y'all tin utilize this icon to pull any incoming commits or push any outgoing commits. You lot tin can too cull to view these commits beginning. To practice so, select the icon, and and then select View Outgoing/Incoming.

    The 2nd icon with the pencil shows the number of uncommitted changes to your code. You tin can select this icon to view those changes in the Git Changes window.

To learn more about how to use Git with your app, encounter the Visual Studio version command documentation.

The finished app

Congratulations! You've completed the code for the reckoner app, built and debugged it, and added it to a repo, all in Visual Studio.

Side by side steps

Learn more than most Visual Studio for C++

The usual starting signal for a C++ developer is a "Hello, world!" application that runs on the control line. That's what you lot'll create in Visual Studio in this commodity, and then we'll move on to something more than challenging: a calculator app.

Prerequisites

  • Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. If it's not installed yet, run across Install C++ back up in Visual Studio.

Create your app project

Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. A projection contains all the options, configurations, and rules used to build your apps. It also manages the human relationship betwixt all the project'south files and any external files. To create your app, beginning, you lot'll create a new projection and solution.

  1. On the menubar in Visual Studio, choose File > New > Project. The New Project window opens.

  2. On the left sidebar, brand sure Visual C++ is selected. In the heart, cull Windows Panel Application.

  3. In the Name edit box at the bottom, proper noun the new projection CalculatorTutorial, then choose OK.

    The New Project dialog.

    An empty C++ Windows console application gets created. Console applications apply a Windows console window to display output and take user input. In Visual Studio, an editor window opens and shows the generated code:

                        // CalculatorTutorial.cpp : This file contains the 'main' function. Plan execution begins and ends there. //  #include "pch.h" #include <iostream>  int chief() {     std::cout << "Hello World!\due north"; }  // Run plan: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Starting time Debugging carte  // Tips for Getting Started: //   1. Utilise the Solution Explorer window to add/manage files //   ii. Use the Team Explorer window to connect to source command //   three. Employ the Output window to come across build output and other messages //   four. Use the Error Listing window to view errors //   five. Become to Projection > Add New Item to create new lawmaking files, or Projection > Add Existing Item to add existing code files to the projection //   6. In the hereafter, to open up this projection once again, go to File > Open > Project and select the .sln file                                      

Verify that your new app builds and runs

The template for a new windows console application creates a elementary C++ "Hullo World" app. At this point, you lot can see how Visual Studio builds and runs the apps you lot create right from the IDE.

  1. To build your projection, cull Build Solution from the Build menu. The Output window shows the results of the build procedure.

    Screenshot Visual Studio with the Output window showing the result of the build process.

  2. To run the lawmaking, on the carte bar, choose Debug, First without debugging.

    Screenshot of the Microsoft Visual Studio Debug Console showing the code ran successfully.

    A panel window opens and and so runs your app. When you first a console app in Visual Studio, it runs your lawmaking, and so prints "Printing any key to continue . . ." to requite you a chance to see the output. Congratulations! You've created your starting time "Hello, world!" console app in Visual Studio!

  3. Press a cardinal to dismiss the console window and render to Visual Studio.

You at present have the tools to build and run your app after every change, to verify that the lawmaking even so works as you expect. Later on, we'll testify yous how to debug it if it doesn't.

Edit the code

Now allow's plow the lawmaking in this template into a estimator app.

  1. In the CalculatorTutorial.cpp file, edit the code to match this example:

                        // CalculatorTutorial.cpp : This file contains the 'chief' role. Program execution begins and ends there. //  #include "pch.h" #include <iostream>  using namespace std;  int main() {     cout << "Calculator Console Application" << endl << endl;     cout << "Delight enter the operation to perform. Format: a+b | a-b | a*b | a/b"         << endl;     return 0; }  // Run program: Ctrl + F5 or Debug > Get-go Without Debugging menu // Debug program: F5 or Debug > Start Debugging carte du jour // Tips for Getting Started: //   1. Use the Solution Explorer window to add/manage files //   2. Apply the Team Explorer window to connect to source control //   3. Use the Output window to see build output and other messages //   4. Use the Mistake List window to view errors //   5. Become to Projection > Add together New Item to create new code files, or Projection > Add Existing Detail to add existing code files to the project //   6. In the time to come, to open this project again, go to File > Open > Project and select the .sln file                                      

    Understanding the code:

    • The #include statements permit you to reference code located in other files. Sometimes, you may encounter a filename surrounded by angle brackets (<>); other times, it'southward surrounded by quotes (" "). In full general, angle brackets are used when referencing the C++ Standard Library, while quotes are used for other files.
    • The #include "pch.h" (or in Visual Studio 2017 and earlier, #include "stdafx.h") line references something known every bit a precompiled header. These are often used by professional programmers to meliorate compilation times, but they are beyond the scope of this tutorial.
    • The using namespace std; line tells the compiler to wait stuff from the C++ Standard Library to exist used in this file. Without this line, each keyword from the library would have to be preceded with a std::, to denote its scope. For instance, without that line, each reference to cout would have to be written as std::cout. The using statement is added to make the code look more clean.
    • The cout keyword is used to print to standard output in C++. The << operator tells the compiler to send whatever is to the correct of it to the standard output.
    • The endl keyword is similar the Enter key; information technology ends the line and moves the cursor to the adjacent line. It is a amend practice to put a \n inside the string (contained by "") to do the same thing, as endl e'er flushes the buffer and can injure the performance of the programme, merely since this is a very small app, endl is used instead for better readability.
    • All C++ statements must terminate with semicolons and all C++ applications must incorporate a principal() function. This function is what the program runs at the first. All code must exist accessible from chief() in order to exist used.
  2. To save the file, enter Ctrl+Southward, or choose the Save icon near the top of the IDE, the floppy disk icon in the toolbar under the menu bar.

  3. To run the application, press Ctrl+F5 or get to the Debug bill of fare and choose Offset Without Debugging. If you lot get a pop-up that says This project is out of date, you may select Do not show this dialog again, and then choose Yes to build your awarding. Y'all should encounter a console window announced that displays the text specified in the code.

    Build and start your application.

  4. Close the console window when you're done.

Add together code to do some math

It'south fourth dimension to add together some math logic.

To add a Computer class

  1. Go to the Project menu and cull Add Class. In the Class Name edit box, enter Reckoner. Choose OK. Two new files get added to your project. To save all your changed files at once, press Ctrl+Shift+S. It's a keyboard shortcut for File > Save All. At that place'due south as well a toolbar button for Salvage All, an icon of ii floppy disks, found abreast the Save button. In general, it's good exercise to do Relieve All often, so y'all don't miss any files when you salvage.

    Short video showing the user opening the Add Class dialog box, typing Calculator in the Class Name field, and selecting O K.

    A class is similar a blueprint for an object that does something. In this case, we define a reckoner and how it should work. The Add Class sorcerer you used above created .h and .cpp files that have the aforementioned name as the form. You can see a total listing of your project files in the Solution Explorer window, visible on the side of the IDE. If the window isn't visible, y'all tin can open it from the carte du jour bar: choose View > Solution Explorer.

    Screenshot of the Solution Explorer window displaying the Calculator Tutorial project.

    You lot should now accept 3 tabs open up in the editor: CalculatorTutorial.cpp, Calculator.h, and Figurer.cpp. If yous accidentally shut one of them, yous tin reopen it by double-clicking it in the Solution Explorer window.

  2. In Calculator.h, remove the Computer(); and ~Figurer(); lines that were generated, since you lot won't need them hither. Next, add the following line of code and so the file now looks like this:

                        #pragma once form Computer { public:     double Calculate(double x, char oper, double y); };                                      

    Understanding the code

    • The line you added declares a new part called Calculate, which nosotros'll use to run math operations for addition, subtraction, multiplication, and partitioning.
    • C++ lawmaking is organized into header (.h) files and source (.cpp) files. Several other file extensions are supported past various compilers, but these are the main ones to know about. Functions and variables are normally declared, that is, given a name and a type, in header files, and implemented, or given a definition, in source files. To admission code divers in another file, yous can use #include "filename.h", where 'filename.h' is the name of the file that declares the variables or functions yous want to use.
    • The two lines you deleted alleged a constructor and destructor for the course. For a simple class like this i, the compiler creates them for you, and their uses are across the scope of this tutorial.
    • Information technology's skilful practice to organize your code into different files based on what it does, and so it's easy to detect the code you demand afterwards. In our case, we define the Computer class separately from the file containing the primary() part, but we program to reference the Calculator class in main().
  3. You'll see a light-green squiggle appear under Calculate. It'due south considering nosotros oasis't defined the Summate part in the .cpp file. Hover over the discussion, click the lightbulb that pops up, and cull Create definition of 'Calculate' in Calculator.cpp. A popular-upward appears that gives you a peek of the code modify that was fabricated in the other file. The lawmaking was added to Calculator.cpp.

    Short video showing the user selecting the Create definition of Calculate in Calculator C P P option.

    Currently, it but returns 0.0. Let'southward change that. Press Esc to close the pop-up.

  4. Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and ~Calculator() sections (as you did in the .h file) and add together the following code to Calculate():

                        #include "pch.h" #include "Calculator.h"  double Calculator::Calculate(double ten, char oper, double y) {     switch(oper)     {         case '+':             return ten + y;         case '-':             return x - y;         case '*':             return x * y;         case '/':             return x / y;         default:             return 0.0;     } }                                      

    Agreement the lawmaking

    • The function Summate consumes a number, an operator, and a second number, then performs the requested operation on the numbers.
    • The switch statement checks which operator was provided, and just executes the case respective to that operation. The default: case is a fallback in instance the user types an operator that isn't accustomed, so the program doesn't interruption. In full general, it's best to handle invalid user input in a more elegant way, merely this is beyond the scope of this tutorial.
    • The double keyword denotes a blazon of number that supports decimals. This way, the figurer can handle both decimal math and integer math. The Calculate function is required to always return such a number due to the double at the very starting time of the code (this denotes the function's return type), which is why we return 0.0 even in the default example.
    • The .h file declares the function prototype, which tells the compiler upfront what parameters it requires, and what return type to expect from information technology. The .cpp file has all the implementation details of the role.

If you lot build and run the code over again at this betoken, it volition nevertheless exit after request which operation to perform. Side by side, you'll modify the main function to practise some calculations.

To telephone call the Calculator course member functions

  1. Now let's update the principal function in CalculatorTutorial.cpp:

                        // CalculatorTutorial.cpp : This file contains the 'master' function. Program execution begins and ends in that location. //  #include "pch.h" #include <iostream> #include "Reckoner.h"  using namespace std;  int chief() {     double x = 0.0;     double y = 0.0;     double consequence = 0.0;     char oper = '+';      cout << "Calculator Console Application" << endl << endl;     cout << "Delight enter the functioning to perform. Format: a+b | a-b | a*b | a/b"          << endl;      Calculator c;     while (true)     {         cin >> x >> oper >> y;         result = c.Calculate(x, oper, y);         cout << "Outcome is: " << result << endl;     }      return 0; }                                      

    Understanding the code

    • Since C++ programs always kickoff at the main() role, nosotros need to call our other code from there, so a #include statement is needed.
    • Some initial variables x, y, oper, and upshot are alleged to shop the get-go number, 2d number, operator, and final issue, respectively. Information technology is always expert practice to give them some initial values to avert undefined behavior, which is what is washed here.
    • The Calculator c; line declares an object named 'c' as an instance of the Calculator class. The class itself is just a design for how calculators work; the object is the specific estimator that does the math.
    • The while (true) statement is a loop. The code inside the loop continues to execute over and over once again as long as the condition inside the () holds truthful. Since the condition is merely listed every bit true , it's always true, so the loop runs forever. To close the programme, the user must manually close the console window. Otherwise, the programme ever waits for new input.
    • The cin keyword is used to accept input from the user. This input stream is smart enough to process a line of text entered in the console window and place it inside each of the variables listed, in guild, bold the user input matches the required specification. You can modify this line to accept dissimilar types of input, for example, more two numbers, though the Calculate() part would also demand to be updated to handle this.
    • The c.Calculate(x, oper, y); expression calls the Calculate function defined earlier, and supplies the entered input values. The function then returns a number that gets stored in consequence.
    • Finally, result is printed to the panel, so the user sees the result of the calculation.

Build and test the code once more

At present it's time to examination the program over again to brand certain everything works properly.

  1. Press Ctrl+F5 to rebuild and start the app.

  2. Enter v + five, and press Enter. Verify that the result is 10.

    Screenshot of the Microsoft Visual Studio Debug Console showing the correct result of 5 + 5.

Debug the app

Since the user is costless to type anything into the console window, let's make sure the calculator handles some input as expected. Instead of running the plan, let's debug information technology instead, and so nosotros can inspect what it's doing in particular, stride-by-pace.

To run the app in the debugger

  1. Set a breakpoint on the result = c.Calculate(x, oper, y); line, just afterward the user was asked for input. To prepare the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. A red dot appears.

    Short video of Visual Studios showing the user creating the red dot that represents a breakpoint.

    Now when nosotros debug the program, it e'er pauses execution at that line. Nosotros already have a rough thought that the program works for uncomplicated cases. Since we don't want to pause execution every time, permit's make the breakpoint conditional.

  2. Right-click the ruby dot that represents the breakpoint, and choose Conditions. In the edit box for the condition, enter (y == 0) && (oper == '/'). Cull the Close button when you lot're done. The condition is saved automatically.

    Short video of Visual Studio 2019 showing the user opening the Breakpoint Settings section and setting a conditional breakpoint.

    Now we pause execution at the breakpoint specifically if a sectionalisation past 0 is attempted.

  3. To debug the plan, press F5, or cull the Local Windows Debugger toolbar button that has the green arrow icon. In your console app, if you enter something like "five - 0", the plan behaves normally and keeps running. Nonetheless, if you type "10 / 0", it pauses at the breakpoint. You tin even put any number of spaces between the operator and numbers; cin is smart enough to parse the input appropriately.

    Short video of Visual Studios showing that the program paused at the conditional breakpoint.

Useful windows in the debugger

Whenever you debug your code, you lot may find that some new windows appear. These windows can assist your debugging experience. Take a look at the Autos window. The Autos window shows yous the current values of variables used at least three lines before and upwardly to the current line.

The Autos window.

To see all of the variables from that part, switch to the Locals window. You tin actually modify the values of these variables while debugging, to see what upshot they would have on the program. In this case, we'll leave them lone.

Screenshot of the Locals window.

You tin also but hover over variables in the code itself to see their current values where the execution is currently paused. Make sure the editor window is in focus by clicking on information technology first.

Short video showing the tooltip that appears displaying the value of the variable.

To continue debugging

  1. The yellow line on the left shows the current point of execution. The current line calls Calculate, and then press F11 to Pace Into the function. You'll notice yourself in the body of the Calculate office. Exist careful with Step Into; if you do it too much, you may waste matter a lot of time. It goes into whatsoever lawmaking yous use on the line you are on, including standard library functions.

  2. Now that the point of execution is at the showtime of the Summate function, printing F10 to movement to the next line in the programme's execution. F10 is also known as Footstep Over. You can use Step Over to movement from line to line, without delving into the details of what is occurring in each part of the line. In general you should utilise Footstep Over instead of Step Into, unless yous want to dive more deeply into code that is existence called from elsewhere (equally you did to reach the body of Summate).

  3. Continue using F10 to Pace Over each line until yous get dorsum to the main() role in the other file, and stop on the cout line.

    Step out of Calculate and check result.

    It looks like the program is doing what is expected: it takes the first number, and divides information technology by the second. On the cout line, hover over the upshot variable or take a await at issue in the Autos window. You lot'll see its value is listed as "inf", which doesn't wait right, so let's set it. The cout line but outputs whatever value is stored in result, so when you step one more line forward using F10, the console window displays:

    Screenshot of the Microsoft Visual Studio Debug Console showing the result of dividing by zero.

    This issue happens considering sectionalisation by cipher is undefined, so the program doesn't have a numerical answer to the requested operation.

To fix the "separate by zero" fault

Allow'southward handle segmentation by zero more than gracefully, so a user tin empathize the problem.

  1. Make the post-obit changes in CalculatorTutorial.cpp. (You can leave the program running every bit you edit, thanks to a debugger feature chosen Edit and Continue):

                        // CalculatorTutorial.cpp : This file contains the 'chief' role. Program execution begins and ends there. //  #include "pch.h" #include <iostream> #include "Calculator.h"  using namespace std;  int primary() {     double ten = 0.0;     double y = 0.0;     double result = 0.0;     char oper = '+';      cout << "Calculator Panel Application" << endl << endl;     cout << "Delight enter the operation to perform. Format: a+b | a-b | a*b | a/b" << endl;      Calculator c;     while (true)     {         cin  >> 10  >> oper  >> y;         if (oper == '/' && y == 0)         {             cout << "Division by 0 exception" << endl;             go on;         }         else         {             result = c.Calculate(x, oper, y);         }         cout << "Result is: " << result << endl;     }      render 0; }                                      
  2. At present press F5 one time. Program execution continues all the way until it has to interruption to ask for user input. Enter 10 / 0 again. Now, a more than helpful message is printed. The user is asked for more than input, and the program continues executing normally.

    Short video of the Microsoft Visual Studio Debug Console showing the final result after changes.

    Notation

    When you lot edit code while in debugging mode, there is a risk of lawmaking becoming stale. This happens when the debugger is still running your one-time code, and has non withal updated it with your changes. The debugger pops up a dialog to inform you when this happens. Sometimes, you may need to press F5 to refresh the lawmaking being executed. In detail, if you brand a change inside a function while the point of execution is within that office, y'all'll need to step out of the function, and then back into information technology again to get the updated code. If that doesn't work for some reason and you lot see an error message, yous tin can stop debugging by clicking on the cerise square in the toolbar nether the menus at the peak of the IDE, then start debugging again by inbound F5 or by choosing the green "play" arrow beside the terminate button on the toolbar.

    Understanding the Run and Debug shortcuts

    • F5 (or Debug > Start Debugging) starts a debugging session if ane isn't already active, and runs the program until a breakpoint is hit or the program needs user input. If no user input is needed and no breakpoint is available to striking, the program terminates and the console window closes itself when the program finishes running. If you have something like a "Hullo World" programme to run, utilise Ctrl+F5 or ready a breakpoint before you enter F5 to keep the window open up.
    • Ctrl+F5 (or Debug > First Without Debugging) runs the application without going into debug mode. This is slightly faster than debugging, and the console window stays open afterward the program finishes executing.
    • F10 (known as Footstep Over) lets you iterate through lawmaking, line-by-line, and visualize how the code is run and what variable values are at each stride of execution.
    • F11 (known as Step Into) works similarly to Step Over, except it steps into whatsoever functions chosen on the line of execution. For example, if the line being executed calls a office, pressing F11 moves the arrow into the body of the function, so you lot tin can follow the function'due south code being run before coming back to the line you started at. Pressing F10 steps over the function call and just moves to the next line; the function call still happens, but the program doesn't suspension to show you what information technology'south doing.

Close the app

  • If it's still running, close the console window for the calculator app.

Congratulations! You've completed the code for the calculator app, and built and debugged it in Visual Studio.

Next steps

Learn more about Visual Studio for C++