C++ オンラインコンパイラ - 即座に実行、テスト、デバッグ

無料のオンライン C++ コンパイラで、ブラウザ上で C++ コードを即座に書いて、コンパイルして、実行できます。学習、クイックテスト、面接準備に最適です。セットアップやインストールは不要です。

💡 初心者のためのC++基本ガイド

1. 変数と定数の宣言

C++では、各変数の型を宣言する必要があります。constを使用して、初期化後に変更できない読み取り専用の値を定義します。

int age = 30;
double pi = 3.14159;
char grade = 'A';
std::string name = "Alice";
bool isActive = true;

// 定数
const int MAX_USERS = 100;
const std::string COMPANY = "CodeUtility";

// constを変更しようとするとコンパイル時エラーが発生します
// MAX_USERS = 200; // ❌ エラー

2. 条件分岐 (if / switch)

ifelse ifelseを使用して分岐します。switchは複数の値に使用します。

int x = 2;
if (x == 1) {
    std::cout << "One\n";
} else if (x == 2) {
    std::cout << "Two\n";
} else {
    std::cout << "Other\n";
}

// switch-case
switch (x) {
    case 1:
        std::cout << "One\n";
        break;
    case 2:
        std::cout << "Two\n";
        break;
    default:
        std::cout << "Other\n";
}

3. ループ

forwhiledo-whileを使用してコードブロックを繰り返します。

for (int i = 0; i < 3; i++) {
    std::cout << i << "\n";
}

int n = 3;
while (n > 0) {
    std::cout << n << "\n";
    n--;
}

4. 配列

配列は同じ型の複数の要素を格納します。

int numbers[3] = {10, 20, 30};
std::cout << numbers[1] << "\n";

5. 配列/ベクタの操作

std::vectorを使用して動的配列を作成します。

#include <vector>

std::vector nums = {1, 2, 3};
nums.push_back(4);
nums.pop_back();

for (int n : nums) {
    std::cout << n << " ";
}

6. コンソール入出力

std::cinを使用して入力し、std::coutを使用して出力します。

std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "\n";

7. 関数

関数は再利用可能なロジックをグループ化します。パラメータと戻り値の型を使用します。

int add(int a, int b) {
    return a + b;
}

std::cout << add(3, 4);

8. マップ

std::mapは辞書のようにキーと値のペアを格納します。

#include <map>

std::map ages;
ages["Alice"] = 30;
std::cout << ages["Alice"];

9. 例外処理

trycatchを使用してランタイムエラーを処理します。

try {
    throw std::runtime_error("Error occurred");
} catch (const std::exception& e) {
    std::cout << e.what();
}

10. ファイル入出力

fstreamを使用してファイルの読み書きを行います。

#include <fstream>

std::ofstream out("file.txt");
out << "Hello File";
out.close();

std::ifstream in("file.txt");
std::string line;
getline(in, line);
std::cout << line;
in.close();

11. 文字列操作

C++の文字列はlength()substr()find()のようなメソッドをサポートしています。

std::string text = "Hello World";
std::cout << text.length();
std::cout << text.substr(0, 5);
std::cout << text.find("World");

12. クラスとオブジェクト

C++はクラスを使用したオブジェクト指向プログラミングをサポートしています。

class Person {
  public:
    std::string name;
    Person(std::string n) : name(n) {}
    void greet() { std::cout << "Hi, I'm " << name; }
};

Person p("Alice");
p.greet();

13. ポインタ

ポインタは他の変数のメモリアドレスを格納します。&を使用してアドレスを取得し、 *を使用してデリファレンス(アドレスの値にアクセス)します。

int x = 10;
int* ptr = &x;

std::cout << "Value of x: " << x << "\n";
std::cout << "Address of x: " << ptr << "\n";
std::cout << "Value from pointer: " << *ptr << "\n";

// ポインタを通じてxを変更
*ptr = 20;
std::cout << "Updated x: " << x << "\n";