C++ を使って問題を解決する場合、入力を処理する必要があり、文字列を数値に変換したり、数値を文字列に変換したりする必要がある場合があります。
C++11 以降では、このような変換は非常に簡単です。
1. 文字列を数値に変換 (文字列を int に変換)
1. 1 ストイ (C++11 以降)
使用法:
#include <iostream> #include <string> int main() { std::string str = "123"; int num; // using stoi() to store the value of str1 to x num = std::stoi(str); std::cout << num; return 0; } ```
1.2 atoi、C++11 より前、または C スタイルの文字列用
使用法:
#include <iostream> // cstdlib is needed for atoi() #include <cstdlib> using namespace std; int main() { // declaring and initializing character array char str[] = "456"; int num = std::atoi(str); std::cout << "num = " << num; return 0; } ```
std::string strの場合
atoi( str.c_str() )
1.3 文字列ストリームの使用
使用法:
#include <iostream>
#include <string>
#include <sstream> // this will allow you to use stringstream in your program
using namespace std;
int main() {
//create a stringstream object, to input/output strings
stringstream ss;
// a variable named str, that is of string data type
string str = "7";
// a variable named num, that is of int data type
int num;
//extract the string from the str variable (input the string in the stream)
ss << str;
// place the converted value to the int variable
ss >> num;
//print to the consloe
cout << num << endl; // prints the intiger value 7
}
シンプルでわかりやすい最初のものを使用することをお勧めします。
2. 数値を文字列に変換します (int から string)。
2.1 to_string()
#include <iostream> #include <string> using namespace std; int main() { int num = 123; std::string str = to_string(num); std::cout << str; return 0; } ```
2.2 文字列ストリーム
#include <iostream> #include<string> #include<sstream> // for using stringstream using namespace std; int main() { int num = 15; // creating stringstream object ss std::stringstream ss; // assigning the value of num to ss ss << num; // initializing string variable with the value of ss // and converting it to string format with str() function std::string strNum = ss.str(); std::cout << strNum; return 0; } ```
2.3 itoa (最初に C スタイルの文字列に変換)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
3. 参考資料:
https://www.freecodecamp.org/news/string-to-int-in-c-how-to-convert-a-string-to-an-integer-example/
https://www.programiz.com/ cpp-programming/string-int-conversion
https://stackoverflow.com/questions/5590381/easyest-way-to-convert-int-to-string-in-c