C++ で文字列を Int 配列に変換する
-
C++ で
std::getlineおよびstd::stoi関数を使用してstringをint配列に変換する -
C++ で
std::string::findおよびstd::stoi関数を使用して、stringをint配列に変換する -
C++ で
std::copyおよびstd::remove_if関数を使用して、stringをint配列に変換する
この記事では、C++ で文字列を int 配列に変換する方法に関する複数の方法を示します。
C++ で std::getline および std::stoi 関数を使用して string を int 配列に変換する
std::stoi は、文字列値を符号付き整数に変換するために使用され、タイプ std::string の必須引数を 1つ取ります。オプションで、関数は 2つの追加の引数を取ることができ、最初の引数を使用して、最後の変換されていない文字のインデックスを格納できます。3 番目の引数は、オプションで入力の基数を指定できます。.csv ファイルのように、入力文字列としてコンマ区切りの数字を想定していることに注意してください。したがって、getline 関数を使用して各数値を解析し、その値を stoi に渡します。また、反復ごとに push_back メソッドを呼び出すことにより、各番号を std::vector コンテナに格納します。
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
using std::stringstream;
using std::vector;
int main(int argc, char *argv[]) {
string text = "125, 44, 24, 5543, 111";
vector<int> numbers;
int num;
stringstream text_stream(text);
string item;
while (std::getline(text_stream, item, ',')) {
numbers.push_back(stoi(item));
}
for (auto &n : numbers) {
cout << n << endl;
}
exit(EXIT_SUCCESS);
}
出力:
125
44
24
5543
111
C++ で std::string::find および std::stoi 関数を使用して、string を int 配列に変換する
または、std::string クラスの find 組み込みメソッドを使用してコンマ区切り文字の位置を取得し、substr 関数を呼び出して数値を取得することもできます。次に、substr の結果が stoi に渡され、stoi 自体が push_back メソッドにチェーンされて、数値が vector に格納されます。シーケンスの最後の番号を抽出するために必要な while ループの後に行があることに注意してください。
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
using std::stringstream;
using std::vector;
int main(int argc, char *argv[]) {
string text = "125, 44, 24, 5543, 111";
vector<int> numbers;
size_t pos = 0;
while ((pos = text.find(',')) != string::npos) {
numbers.push_back(stoi(text.substr(0, pos)));
text.erase(0, pos + 1);
}
numbers.push_back(stoi(text.substr(0, pos)));
for (auto &n : numbers) {
cout << n << endl;
}
exit(EXIT_SUCCESS);
}
出力:
125
44
24
5543
111
C++ で std::copy および std::remove_if 関数を使用して、string を int 配列に変換する
整数を抽出する別の方法は、std::copy アルゴリズムを std::istream_iterator および std::back_inserter と組み合わせて使用することです。このソリューションは、文字列値を vector に格納し、それらを cout ストリームに出力しますが、std::stoi 関数を簡単に追加して、各要素を int 値に変換できます。ただし、次のサンプルコードでは、数値は文字列値としてのみ格納されることに注意してください。
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
using std::stringstream;
using std::vector;
int main(int argc, char *argv[]) {
string text = "125, 44, 24, 5543, 111";
vector<string> nums;
std::istringstream iss(text);
copy(std::istream_iterator<string>(iss), std::istream_iterator<string>(),
std::back_inserter(nums));
for (auto &n : nums) {
n.erase(std::remove_if(n.begin(), n.end(), ispunct), n.end());
cout << n << endl;
}
exit(EXIT_SUCCESS);
}
出力:
125
44
24
5543
111
