Skip to main content

Online C++ Compiler

main.cpp
Ready

About C++

C++ adds classes and the Standard Template Library (vectors, maps, sorting) to C. It's the most common language for competitive programming and DSA practice.

How to take input in C++

cin >> reads one value at a time and skips spaces and new lines. Use getline(cin, s) for a whole line with spaces.

int n;  cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
string line;  getline(cin >> ws, line);   // a full line

C++ programs to try

Copy one into the editor above, put any input in the Input tab and press Run.

Sort and remove duplicates

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n; cin >> n;
    vector<int> a(n);
    for (int &x : a) cin >> x;
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
    for (int x : a) cout << x << " ";
    cout << endl;
}

Input: 7 ⏎ 5 3 5 1 3 9 1

Count word frequency with map

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<string, int> freq;
    string w;
    while (cin >> w) freq[w]++;
    for (auto &[word, c] : freq) cout << word << ": " << c << endl;
}

Input: to be or not to be

Binary search

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, target; cin >> n;
    vector<int> a(n);
    for (int &x : a) cin >> x;
    cin >> target;
    bool found = binary_search(a.begin(), a.end(), target);
    cout << (found ? "Found" : "Not found") << endl;
}

Input: 6 ⏎ 2 4 7 10 15 21 ⏎ 10

Common C++ errors and how to fix them

Segmentation fault
Usually an index past the end of an array or vector. Check loop bounds, and that the vector has been sized before writing to it.
error: 'vector' was not declared in this scope
Add #include <vector> (or #include <bits/stdc++.h>) and using namespace std;.
Wrong answer with large numbers
int overflows above about 2.1 billion. Use long long for big sums and products.
error: expected ';' before ...
A statement is missing its semicolon, usually on the line before the one named.

Frequently asked questions

Is this online C++ compiler free?

Yes. Write and run C++ code in your browser for free, with nothing to install and no setup.

How do I give input to my C++ program?

Type it in the Input tab before pressing Run, and read it with cin. Values can be separated by spaces or new lines.

Can I use bits/stdc++.h and the STL?

Yes. #include <bits/stdc++.h> works, along with vector, map, set, sort, queue and the rest of the standard library.

Does it work on my phone?

Yes. The editor, input and output work in a mobile browser, so you can practise C++ without a laptop.