Menu
CoddyTech

出力、コメント、Main

Coddyの「C++開発者のためのC#」コースのレッスン 2/48。

C++のストリーム挿入はConsole.WriteLineに相当します。C#ではグローバル関数ではなく、クラス内のstatic Mainを使います。おなじみの波括弧とコメントはそのままですが、出力APIと型メンバーの検索方法は異なります。

Console.WriteLineは1行を出力します。文字列は二重引用符で囲み、//コメントはソース行の末尾まで続きます。波括弧はクラスまたはメソッドの本体を囲み、セミコロンは文の末尾に付けます。static Mainメソッドがエントリーポイントですが、ヘルパーメソッドは別のファイルに置き、出力せずにデータを返すことができます。

C++の参照例

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
cout << string("Hi, ") + "Mina" << "\n"; // コメント
}

Main内のC#の文

Console.WriteLine("Hi, " + "Mina"); // コメント

これらは要点を絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。

参照出力:

Hi, Mina

C#の出力:

Hi, Mina
challenge icon

チャレンジ

簡単

入力は1行で、空の場合もあります。Hello の後にスペースを置き、名前を正確に続けて、感嘆符を付けて返してください。ロックされた Main は、返された文字列を1回出力します。ヘルパーから出力しないでください。

ロック解除された C# ファイルを編集してください。表示されているロックされた Main.cs は、説明されている行を読み取り、Exercise.Solve を呼び出し、入力が変更されていないことを確認して、最後に改行を1つ付けて結果を出力します。宣言済みの API を維持してください。2つ目の Main を追加したり、診断出力を出したりしないでください。

自分で試してみよう

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ