How can I set up a default code for C++ in visual studio code?

Viewed 19667

In CodeBlocks it is possible to set up a code that will open each time you create a new file. Kind of a code template or skeleton.

How can I set up a default code to open in Visual Studio Code C++ so I don't have to write it each time I create a new file? I mean, instead of creating a blank file, I need it to show the following code:

#include <iostream>

using namespace std;

int main(){

}
3 Answers
  1. Go to this link.

  2. Type/Paste the default code you want to use the snippet for. Enter the trigger and description.

  3. Copy the generated snippet onto clipboard.

  4. Head to VSC. Press ctr + shift + p .Type configure user snippets. 5.Select your desired language(C++ in your case).

  5. Replace the comments with the snippet in your clipboard.

  6. Save and exit. Now try to type the trigger text. You will see the snippet ready!

You can use the File Template extension.

C++ files are not included in its default list of supported file types. But it does support adding your own templates for known VS Code language identifiers, such as .cpp for C++ files.

To set it up, follow the instructions on the extension's page:

  1. Install the extension
  2. Go to the extension's templates directory
    gino@templates$ pwd
    /Users/gino/.vscode/extensions/ralfzhang.filetemplate-2.0.4/asset/templates
    
  3. Create a file named cpp.tmpl
  4. Write your template code
    gino@templates$ vim cpp.tmpl
    
    gino@templates$ cat cpp.tmpl
    #include <iostream>
    
    using namespace std;
    
    int main(){
    
    }
    

To use it:

  1. Restart VS Code (might not be needed, but just to be sure)
  2. Create a file with a .cpp extension
  3. Open the command list (CMD+Shift+P on Mac or Ctrl+Shift+P on Linux/Windows)
  4. Run the command "Tmpl: Create Template"

enter image description here

The .cpp file will be populated by the contents of cpp.tmpl.

enter image description here

If you want to be fancy with your template, according to the extension's documentation, the template follows the TextMate syntax. In my example above, I just used plain C++ code and it worked OK.

you can setup user snippet.

1) click on setting icon select user snippets.

enter image description here

2) select your language,cpp.

enter image description here

now enter snippet code,

(snippet code is in JSON)

// Write this code in the cpp.json file
{
    "cpp snippets":
    {
        "prefix" : "basic",
                   "body" : [
                       "#include<iostream>",
                       "using namespace std;",
                       "int main()",
                       "{",
                       "    return 0;",
                       "}"
  
                   ],
                            "description" : "c++ basic"
    }
}

Save this file, now open new .cpp file and just enter "basic" your snippet will appear !

to create custom snippet code, check this

Related