Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++でstringで読み込んだ数列を一桁ずつint型へ変換

Last updated at Posted at 2017-01-12

入力されたstring型の数列に対して、一桁ずつ(0~9の範囲で)計算処理したかったのでその方法を自分用に簡易メモ。

StringToInt.cpp
#include <iostream>
#include <string>
using namespace std;

int main(void) {

    string str;   //今回は15文字入力と予めわかっている
    int N[15];

    cin >> str;

    for (int i = 0; i < 15; ++i) {

        N[i] = (int)(str[i] - '0');  //str[i] はchar型なのでchar→intへ変換

        cout << N[i] << endl;  //確認のため表示
	    
    }

    return 0;
}

ちなみに数列内に文字が混在している時は、0~9以外の数値を無視する、などで除外することができるのではないでしょうか。

##追記(2017/01/15)
SaitoAtsushi さんから頂いたコメントで、transformという関数が使えることがわかったので、試してみました。

StringToInt.cpp

#include <iostream>
#include <string>
#include <algorithm>   //新たにインクルード

using namespace std;

int main(void) {

	string str;  
	int N[15];

	cin >> str;

	transform(begin(str), end(str), N, [](char c) {return c - '0'; });

	for (int i = 0; i < 15; ++i) {
		cout << N[i] << endl;       //確認用
	}

	return 0;
}

この方法でも同様の結果が得られました。ありがとうございました。

8
8
6

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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?