文字の ASCII 値を求める

C++C++Beginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C++ プログラミング言語で文字の ASCII 値を見つける方法を学びます。型キャストの概念を使って、変数にアクセスする際にそのデータ型を変更します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/strings("Strings") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/variables -.-> lab-96136{{"文字の ASCII 値を求める"}} cpp/strings -.-> lab-96136{{"文字の ASCII 値を求める"}} cpp/output -.-> lab-96136{{"文字の ASCII 値を求める"}} cpp/user_input -.-> lab-96136{{"文字の ASCII 値を求める"}} cpp/files -.-> lab-96136{{"文字の ASCII 値を求める"}} cpp/code_formatting -.-> lab-96136{{"文字の ASCII 値を求める"}} end

C++ ファイルの作成

ターミナルを開き、~/project ディレクトリに新しい main.cpp という名前のファイルを作成します。

cd ~/project
touch main.cpp

コードの記述

以下のコードをコピーして main.cpp ファイルに貼り付けます。

#include <iostream>

using namespace std;

int main()
{
    //変数宣言 - char 型の変数は 1 文字の入力を受け取ります
    char c;

    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << "===== Program to Find the ASCII value of a character ===== \n\n";

    //ユーザー入力を受け取る
    cout << "Enter a character : ";
    cin >> c;

    //入力された文字の ASCII 値を表示する
    cout << "\nThe ASCII value of the entered character is : " << (int)c << "\n\n";

    return 0;
}

コードのコンパイルと実行

コードをコンパイルして実行するには、ターミナルで次のコマンドを実行します。

g++ main.cpp -o main &&./main

コードのテスト

出力は次のようになるはずです。

Welcome to LabEx :-)


===== Program to Find the ASCII value of a character =====

Enter a character : B

The ASCII value of the entered character is : 66

まとめ

おめでとうございます!文字の ASCII 値を求める C++ プログラムを正常に作成しました。この実験では、型キャストと変数にアクセスしながらそのデータ型を変更する方法について学びました。文字の ASCII 値は一意であり、さまざまなアプリケーションで使用できることを忘れないでください。