基本
基本
c++ではプログラムの開始はmain関数から始まります。
以下のサンプルはiostreamライブラリのcoutを使用して標準出力を行います。
// sample01-01.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
// ライブラリ読み込み
#include <iostream>
using namespace System;
using namespace std;
int main(array<System::String ^> ^args)
{
// テスト
cout << "Hello, World!1";
cout << "Hello, World!2" << endl;
return 0;
}
名前空間
ライブラリ間で同じ命令が重複しないようにするために、ライブラリの関数を使用する場合は
名前空間を指定する必要があります。
しかし、using namespaceを定義することで名前空間を省略することも可能
// sample01-02.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include <iostream>
// using namespaceに定義した場合は省略が可能
using namespace System;
using namespace std;
int main(array<System::String ^> ^args)
{
// namespaceを指定して出力
std::cout << "Hello world-01" << std::endl;
// 上記で指定しているので省略する
cout << "Test Hello" << endl;
// 返却
return 0;
}
コメント
指定の行のみをコメントにしたい場合は「//」を文の先頭に設定
複数の範囲をコメントにしたい場合は「/* ~ */」を設定
// sample01-03.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include <iostream>
using namespace System;
int main(array<System::String ^> ^args)
{
std::cout << "Test Message1" << std::endl;
// ↓はコメント行
// std::cout << "Test Message2" << std::endl;
std::cout << "Test Message3" << std::endl;
// ↓はコメント行
//std::cout << "Test Message4" << std::endl;
std::cout << "Test Message5" << std::endl;
/* ここからコメント
std::cout << "Test Message6" << std::endl;
std::cout << "Test Message7" << std::endl;
ここまでコメント */
std::cout << "Test Message8" << std::endl;
return 0;
}
文字、数値
文字の場合は'(シングルクォート)で挟む
文字列の場合は"(ダブルクォート)で挟む
数値の場合はなし
// sample01-04.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include <iostream>
using namespace System;
int main(array<System::String ^> ^args)
{
// 文字を出力
std::cout << "文字:" << 'a' << std::endl;
// 文字列を出力
std::cout << "文字列リテラルを出力:" << "あああ" << std::endl;
// 数値リテラルを出力
std::cout << "数値リテラルを出力:" << 9999 << std::endl;
return 0;
}
エスケープシーケンス
改行やタブ、¥、”などを表示したい場合はそのままでは出力できないので
エスケープシーケンスとして出力する必要がある
// sample01-05.cpp : メイン プロジェクト ファイルです。
#include "stdafx.h"
#include <iostream>
using namespace System;
int main(array<System::String ^> ^args)
{
// 改行出力
std::cout << "あああ\nいいい\nううう" << std::endl;
// タブ
std::cout << "かかか\tききき\tくくく" << std::endl;
// ダブルクォートおよび¥
std::cout << "\"c:\\test.dat\"" << std::endl;
/* 出力結果サンプル
あああ
いいい
ううう
かかか ききき くくく
"c:\test.dat"
*/
return 0;
}
| エスケープシーケンス |
説明 |
| ¥n |
改行 |
| ¥t |
タブ |
| ¥b |
バックスペース |
| ¥r |
キャリッジリターン |
| ¥f |
ページフィールド |
| ¥’ |
シングルクォーテーション |
| ¥” |
ダブルクォーテーション |
| ¥0 |
NULL |
| ¥¥ |
円記号 |
| ¥? |
クエスチョンマーク |
| ¥a |
ベル音(alert) |
| ¥xhh |
16進拡張 |
| ¥ooo |
8進拡張 |
最終更新:2011年09月02日 11:01