0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】string型の文字列からchar型を取り出す

Last updated at Posted at 2025-01-20

与えられた文字列から一文字ずつのASCIIコードを取り出して計算したかった時に詰まったので備忘録として書きます。

やりたかったこと

string key

が文字列として与えられた時に、この文字の一つずつをchar型として取り出してASCIIコードの足し算をしたい。

実装方法

結論範囲for文で文字を一つずつ取り出せます。
また、取り出した文字は変換することなく足し算できます。

int型とchar型の足し算や、char型どうしの足し算ではchar型が自動的にint型に変換されるため問題なく計算ができます。

//合計の変数を作る
int sum{0};
//文字から文字を取り出してASCIIコードの合計を求める
for(char ch : key){
    sum += ch;
}

調べても記事があまりなかったので書きました。何か間違っていることがあれば教えてください🐢

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?