はじめに
Hello World
すべての C++ プログラムは main() から始まります。<iostream> は std::cout(標準出力)と std::cin(標準入力)を提供します。std:: プレフィックスは標準名前空間を参照します;using namespace std; で回避できますが、グローバル名前空間を汚染するためヘッダでは推奨されません。
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}変数と auto
auto は初期化子から型を推論します(C++11)。型が明らかまたは冗長な場合(イテレータ)に auto を使用します。const は値を不変にし;constexpr はコンパイル時に評価し、バイナリに埋め込まれる真の定数にします。
int age = 30;
double pi = 3.14159;
char grade = 'A';
bool is_dev = true;
std::string name = "Alice";
auto x = 42; // int
auto y = 3.14; // double
const double TAX = 0.08;入力と出力
std::getline はスペースを含む完全な行を読み取りますが、std::cin >> は空白で停止します。両者を混用するとバッファに改行が残ります;getline と >> の間に std::cin.ignore() を呼び出して破棄してください。
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Name: ";
std::getline(std::cin, name);
std::cout << "Age: ";
std::cin >> age;
std::cout << "Hi " << name << ", " << age << "\n";
}参照
参照は初期化時に必ず割り当てられ、別のオブジェクトに再割り当てできないエイリアスです。参照渡しはコピーを回避し、呼び出し側の変数を変更できます。高コストなコピーを避けるため、読み取り専用パラメータには const T& を使用します。
int x = 10;
int &ref = x; // alias for x
ref = 20;
std::cout << x; // 20
void increment(int &n) { n++; }
int a = 5;
increment(a); // a is now 6型変換
C スタイルのキャストより static_cast を優先してください — 明示的でコンパイル時にチェックされ、意図が明確になります。std::stoi、std::stod は文字列を数値に変換;std::to_string は逆を行います。不正入力での std::out_of_range に注意してください。
double d = 3.99;
int i = (int)d; // C-style: 3
int j = static_cast<int>(d); // C++: 3
int n = 65;
char c = static_cast<char>(n); // 'A'
// string <-> number
int num = std::stoi("42");
std::string s = std::to_string(3.14);文字列
std::string の基礎
std::string は自身のメモリを管理し、必要に応じて成長します。C の char 配列とは異なり、長さを手動管理しません。.find() は部分文字列が見つからない場合 std::string::npos(巨大な値)を返すため、常に npos と比較してください。
#include <string>
std::string s = "Hello";
std::cout << s.length(); // 5
std::cout << s[0]; // H
s += ", World!";
std::cout << s; // Hello, World!
std::cout << s.substr(0, 3); // Hel
std::cout << s.find("World"); // 7比較と検索
比較は辞書順です。.find() は前方検索、.rfind() は後方検索します。両方とも見つからない場合 std::string::npos を返すため、結果を boolean として扱うのではなく常に npos と比較してください。
std::string a = "apple", b = "banana";
if (a == b) { /* equal */ }
if (a < b) { /* apple comes before banana */ }
if (a.find("pp") != std::string::npos) {
std::cout << "found\n";
}
size_t pos = a.rfind("p"); // last occurrenceStringstream
stringstream は文字列と型付き値の橋渡しをし、フォーマットされた文字列の構築(バッファのような)や空白区切りのトークンの解析に便利です。直接操作より遅いですが、シリアライズとデシリアライズに非常に柔軟です。
#include <sstream>
// Build a string
std::ostringstream oss;
oss << "Name=" << "Alice" << "&Age=" << 30;
std::string result = oss.str();
// Parse tokens
std::istringstream iss("10 20 30");
int a, b, c;
iss >> a >> b >> c; // a=10, b=20, c=30Raw 文字列と複数行
Raw 文字列リテラル R"(...)" はバックスラッシュと引用符を文字通りに扱い、正規表現パターン、Windows ファイルパス、JSON/XML テンプレートに最適です。括弧内の区切り文字は任意で、例えば R"x(...)x" で ) を内部に含められます。