C++サンプルプログラム 例1)2つの整数の加算 //program file name: ex01.cpp #include using namespace std; int main() { int a, b, sum; cout << "a: "; cin >> a; cout << "b: "; cin >> b; sum = a + b; cout << "a+b=" << sum << "\n"; return 0; } 例2)文字列の読み込みと表示 //program file name: ex02.cpp #include using namespace std; int main() { char namae[128]; cout << "Your Name: "; cin >> namae; cout << "Hello, " << namae << "!\n"; return 0; } (例2の別バージョン) //program file name: ex02_2.cpp #include #include using namespace std; int main() { string namae = ""; cout << "Your Name: "; cin >> namae; cout << "Hello, " << namae << "!\n"; return 0; }  例3)if文による2つの整数の比較 //program file name: ex03.cpp #include using namespace std; int main() { int a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b; if (a < b) { cout << "a is less than b.\n"; } else if (a == b) { cout << "a is equal to b.\n"; } else { cout << "a is greater than b.\n"; } return 0; } 例4)for文による繰り返し //program file name: ex04.cpp #include using namespace std; int main() { int n, a; cout << "a: "; cin >> a; for (n=1; n<=a; n++) { cout << n << "\n"; } return 0; } 例4−2)繰り返しによる階乗の計算 //program file name: ex04_2.cpp #include using namespace std; int main() { int n; long a, kaijou; cout << "a: "; cin >> a; kaijou = 1; for (n=1; n using namespace std; int main() { int atai[6]; int n; for (n=1; n<=5; n++) { cout << "kotai " << n << ": "; cin >> atai[n]; } cout << "\n"; for (n=1; n<=5; n++) { cout << "kotai " << n << ": atai=" << atai[n] << "\n"; } return 0; } 例5−2)配列変数に数値を入力し,任意の値を呼び出す //program file name: ex05_2.cpp #include using namespace std; int main() { int atai[11]; int n; for (n=1; n<=10; n++) { cout << "kotai " << n << ": "; cin >> atai[n]; } cout << "\n"; while (1) { //無限ループ cout << "kotai bango: "; cin >> n; if ((n <= 0) || (10 < n)) break; cout << atai[n] << "\n"; } return 0; } 例6)ファイルへの書き出し //program file name: ex06.cpp #include #include using namespace std; int main () { char filename[32], mystr[80]; cout << "file name: "; cin >> filename; //cin.getline(filename, 31); cout << "contents: "; cin >> mystr; //cin.getline(mystr, 79); ofstream fout(filename); if (!fout) { cerr << "Cannot open output file.\n"; return 1; } fout << mystr; fout.close(); return 0; } 例7)ファイルからの読み込み //program file name: ex07.cpp #include #include using namespace std; int main () { char filename[32], mystr[80]; cout << "file name: "; cin >> filename; ifstream fin(filename); if (!fin) { cout << "Cannot open output file.\n"; return 1; } fin >> mystr; //fin.getline(mystr, 79); fin.close(); cout << mystr << "\n"; return 0; }