■C++: 基本的なプログラム
■名前空間を指定
$ vi hello.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
「std::cout」のような命令を「cout」と書くことができるようになる
■出力
$ vi output.cpp
#include <iostream>
using namespace std;
int main()
{
cout << 7 << " : " << 3.14 << endl;
cout << "Hello " << "C " << "Lang " << "World!" << endl;
return 0;
}
「iostream」で定義された「cout」に出力演算子「<<」で値を与えると、画面に表示できる
「cout」はC言語と同様に、「sprinf」などでも出力できる
「 << endl;」部分はC言語と同様に、「 << "\n";」でも改行できる
■改行
std::endlと\nの違い|C++のHelloWorldを理解するための本
https://zenn.dev/masahiro_toba/books/a7d0c3d685a209/viewer/208ab9
C++で、std::endl と \n はどっちを使ったほうがいいですか? - Quora
https://jp.quora.com/C-%E3%81%A7-std-endl-%E3%81%A8-n-%E3%81%AF%E3%81%A9%E3%81%A3%E3%81%A1%E3%82%92%...
■入出力
$ vi input.cpp
#include <iostream>
using namespace std;
int main()
{
char str[128];
cout << "名前を入力してください>";
cin >> str;
cout << "ようこそ!" << str << "さん。" << endl;
return 0;
}
$ ./input
名前を入力してください>test
ようこそ!testさん。
「iostream」で定義された「cin」から出力演算子「>>」で値を受け取ると、変数に代入できる
ホワイトスペース(改行や半角スペースなど)が入力の区切りとみなされる
以下のようにすると、複数の値を受け取ることができる
$ vi input2.cpp
#include <iostream>
using namespace std;
int main()
{
int x, y;
cout << "2つの値を加算します>";
cin >> x >> y;
cout << x + y << endl;
return 0;
}
$ ./input2
2つの値を加算します>2 3
5
■ファイル入出力
以下でファイルを読み込むことができる
あらかじめ file.txt を作成し、適当な内容を記述しておく
$ vi read.cpp
#include <fstream>
#include <iostream>
#include <string>
int main()
{
// 読み込むファイルのパスを指定
std::ifstream file("file.txt");
std::string line;
// 1行ずつ読み込む
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
// ファイルを閉じる
file.close();
return 0;
}
以下でファイルに書き込むことができる
あらかじめ fruits.txt を作成しておく(内容はカラでいい)
$ vi write.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main()
{
// 書き出すファイルのパスを指定
std::ofstream file("fruits.txt");
std::vector<std::string> fruits = { "apple", "strawberry", "pear", "grape" };
// 書き出し
for (const auto fruit : fruits) {
file << fruit << std::endl;
}
// ファイルを閉じる
file.close();
return 0;
}
■テンプレート関数
異なるデータ型の値を受け取り、同じ処理を行うことができる
$ vi template.cpp
#include <iostream>
using namespace std;
template <typename X> void println(X out) {
cout << out << endl;
}
int main()
{
println("Hello, World!");
println(10);
println(3.14);
return 0;
}
以下のようにすれば、複数の値を受け取ることもできる
$ vi template2.cpp
#include <iostream>
using namespace std;
template <typename X1, typename X2> void println(X1 out1, X2 out2) {
cout << out1 << " : " << out2 << endl;
}
int main()
{
println("Hello, World!", 10);
println("Hello, World!", 3.14);
return 0;
}
■メモリの動的確保
C言語では malloc() でメモリを動的に確保できるが、C++ではあまり推奨されない
C++の場合、new で動的にメモリを確保できる
確保したメモリは delete で開放できる
$ vi memory.cpp
#include <iostream>
using namespace std;
int main()
{
int *p;
p = new int;
*p = 100;
cout << "動的に割り当てたメモリの内容: " << *p << endl;
delete p;
return 0;
}
動的メモリの割り当て
http://wisdom.sakura.ne.jp/programming/cpp/cpp29.html