std:: 문자열을 int로 변환하려면 어떻게 해야 하나요?
문자열을 int로 변환하고 싶은데 ASCII 코드가 아닙니다.
간단한 설명을 위해 방정식을 문자열로 전달합니다.우리는 그것을 분해하고, 그것을 올바르게 포맷하고, 선형 방정식을 풀어야 한다.이 경우 문자열을 int로 변환할 수 없습니다.
문자열은 (-5) 또는 (25) 등의 형식으로 되어 있기 때문에, 반드시 int입니다.하지만 어떻게 끈에서 그걸 추출하지?
한 가지 방법은 스트링에 for/while 루프를 실행하여 숫자를 체크하고 그 뒤에 모든 숫자를 추출한 후 선두의 '-'가 있는지 확인합니다.있는 경우 int에 -1을 곱합니다.
그런 작은 문제치고는 좀 복잡한 것 같아요.좋은 생각 있어요?
에는 C++11의 새로운 변환 .std::string번호 타입으로 변환합니다.
그래서 대신
atoi( str.c_str() )
사용할 수 있습니다.
std::stoi( str )
서 ''는str로서 당신의 번호입니다.std::string.
숫자에 대한 .long stol(string),float stof(string),double stod(string),... http://en.cppreference.com/w/cpp/string/basic_string/stol 를 참조해 주세요.
사용 가능한 옵션은 다음과 같습니다.
1. sscanf()
#include <cstdio>
#include <string>
int i;
float f;
double d;
std::string str;
// string -> integer
if(sscanf(str.c_str(), "%d", &i) != 1)
// error management
// string -> float
if(sscanf(str.c_str(), "%f", &f) != 1)
// error management
// string -> double
if(sscanf(str.c_str(), "%lf", &d) != 1)
// error management
이는 오류(cppcheck로도 표시됨)입니다. "필드 폭 제한이 없는 스캔프는 libc의 일부 버전에서 대량의 입력 데이터와 함께 크래시할 수 있습니다"(여기와 여기를 참조하십시오).
2. 표준:: sto()*
#include <iostream>
#include <string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(str);
// string -> float
float f = std::stof(str);
// string -> double
double d = std::stod(str);
} catch (...) {
// error management
}
이 솔루션은 짧고 우아하지만 C++11 준거 컴파일러에서만 사용할 수 있습니다.
3. 스트림
#include <string>
#include <sstream>
int i;
float f;
double d;
std::string str;
// string -> integer
std::istringstream ( str ) >> i;
// string -> float
std::istringstream ( str ) >> f;
// string -> double
std::istringstream ( str ) >> d;
// error management ??
단, 이 솔루션에서는 잘못된 입력을 구별하기 어렵습니다(여기를 참조).
4. Boost의 Lexical_cast
#include <boost/lexical_cast.hpp>
#include <string>
std::string str;
try {
int i = boost::lexical_cast<int>( str.c_str());
float f = boost::lexical_cast<int>( str.c_str());
double d = boost::lexical_cast<int>( str.c_str());
} catch( boost::bad_lexical_cast const& ) {
// Error management
}
은 단지 입니다.sstream에서는 「사용할 수 없다」를 하도록 권장하고 sstream에러 관리를 개선합니다(여기를 참조).
5. strto()*
이 솔루션은 오류 관리로 인해 매우 오래 걸리며, 여기에 설명되어 있습니다.플레인 int를 반환하는 함수는 없기 때문에 정수의 경우 변환이 필요합니다(이 변환 방법에 대해서는 여기를 참조).
6. 품질
#include <QString>
#include <string>
bool ok;
std::string;
int i = QString::fromStdString(str).toInt(&ok);
if (!ok)
// Error management
float f = QString::fromStdString(str).toFloat(&ok);
if (!ok)
// Error management
double d = QString::fromStdString(str).toDouble(&ok);
if (!ok)
// Error management
결론들
은 C이라고 하는 C++11이라고 하는 입니다.std::stoi()또는 두 번째 옵션으로서 Qt 라이브러리를 사용하는 것입니다.다른 솔루션은 모두 권장되지 않거나 버그가 있습니다.
std::istringstream ss(thestring);
ss >> thevalue;
완전히 수정하려면 오류 플래그를 확인해야 합니다.
함수를 사용하여 문자열을 정수로 변환합니다.
string a = "25";
int b = atoi(a.c_str());
좀 더 자세히 하기 위해 (그리고 댓글로 요청하신 바와 같이) 를 사용하여 C++17에서 제공하는 솔루션을 추가합니다.
std::string str = "10";
int number;
std::from_chars(str.data(), str.data()+str.size(), number);
변환이 성공했는지 여부를 확인하는 경우:
std::string str = "10";
int number;
auto [ptr, ec] = std::from_chars(str.data(), str.data()+str.size(), number);
assert(ec == std::errc{});
// ptr points to chars after read number
게다가 이러한 솔루션의 퍼포먼스를 비교하려면 , 이 퀵 벤치의 링크를 참조해 주세요. std::from_chars '빠른'입니다.std::istringstream장장느느느느느
1. std::stoi()
std::string str = "10";
int number = std::stoi(str);
2. 스트링 스트림
std::string str = "10";
int number;
std::istringstream(str) >> number;
3. boost::lexical_cast
#include <boost/lexical_cast.hpp>
std::string str = "10";
int number;
try
{
number = boost::lexical_cast<int>(str);
std::cout << number << std::endl;
}
catch (boost::bad_lexical_cast const &e) // Bad input
{
std::cout << "error" << std::endl;
}
4. std::atoi()
std::string str = "10";
int number = std::atoi(str.c_str());
5. sscanf()
std::string str = "10";
int number;
if (sscanf(str .c_str(), "%d", &number) == 1)
{
std::cout << number << '\n';
}
else
{
std::cout << "Bad Input";
}
예를 들어 다음과 같습니다.
다음 예제에서는 명령줄 인수를 일련의 수치 데이터로 취급합니다.
int main(int argc, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
...
}
물론, 내 해결책은 음의 정수에는 효과가 없지만, 정수를 포함하는 입력 텍스트에서 모든 양의 정수를 추출할 것입니다.그것은 을 이용한다.numeric_only★★★★★★★★★★★★★★★★★★:
int main() {
int num;
std::cin.imbue(std::locale(std::locale(), new numeric_only()));
while ( std::cin >> num)
std::cout << num << std::endl;
return 0;
}
입력 텍스트:
the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
출력 정수:
5
25
7987
78
9878
★★★★numeric_only는 다음과 같습니다
struct numeric_only: std::ctype<char>
{
numeric_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
return &rc[0];
}
};
온라인 데모 완료 : http://ideone.com/dRWSj
C++11에서는 stoi 함수를 사용하여 문자열을 int로 변환할 수 있습니다.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "16";
string s2 = "9.49";
string s3 = "1226";
int num1 = stoi(s1);
int num2 = stoi(s2);
int num3 = stoi(s3);
cout << "stoi(\"" << s1 << "\") is " << num1 << '\n';
cout << "stoi(\"" << s2 << "\") is " << num2 << '\n';
cout << "stoi(\"" << s3 << "\") is " << num3 << '\n';
return 0;
}
살상일지도 boost::lexical_cast<int>( theString )일을 잘 해야 할 것 같아요.
답은 많고 가능성은 많아요여기서 놓치고 있는 것은 문자열을 다른 C++ 적분 타입(short, int, long, bool 등)으로 변환하는 범용 메서드입니다.저는 다음과 같은 해결책을 생각해냈습니다.
#include<sstream>
#include<exception>
#include<string>
#include<type_traits>
using namespace std;
template<typename T>
T toIntegralType(const string &str) {
static_assert(is_integral<T>::value, "Integral type required.");
T ret;
stringstream ss(str);
ss >> ret;
if ( to_string(ret) != str)
throw invalid_argument("Can't convert " + str);
return ret;
}
다음은 사용 예를 제시하겠습니다.
string str = "123";
int x = toIntegralType<int>(str); // x = 123
str = "123a";
x = toIntegralType<int>(str); // throws exception, because "123a" is not int
str = "1";
bool y = toIntegralType<bool>(str); // y is true
str = "0";
y = toIntegralType<bool>(str); // y is false
str = "00";
y = toIntegralType<bool>(str); // throws exception
stringstream 출력 연산자를 사용하여 문자열을 통합 유형으로 변환하면 어떨까요?답은 다음과 같습니다.문자열에 의도된 적분 유형의 제한을 초과하는 값이 포함되어 있다고 가정합니다.Examle의 경우 Wndows 64의 최대 int는 2147483647입니다.문자열에 max int + 1: string str = "2147483648" 값을 할당합니다.여기서 문자열을 int로 변환하는 경우:
stringstream ss(str);
int x;
ss >> x;
x 는 2147483647 이 됩니다.이것은 분명히 에러입니다.2147483648 문자열은 int 2147483647로 변환되어서는 안 됩니다.IntegralType에 제공된 함수는 이러한 오류를 발견하고 예외를 발생시킵니다.
Windows 에서는, 다음의 기능을 사용할 수 있습니다.
const std::wstring hex = L"0x13";
const std::wstring dec = L"19";
int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
std::cout << ret << "\n";
}
if (StrToIntEx(dec.c_str(), STIF_SUPPORT_HEX, &ret)) {
std::cout << ret << "\n";
}
strtol ,stringstream16진수를 해석할 필요가 있는 경우는, 밑수를 지정할 필요가 있습니다.
이 질문이 아주 오래된 건 알지만 더 좋은 방법이 있을 것 같아요
#include <string>
#include <sstream>
bool string_to_int(std::string value, int * result) {
std::stringstream stream1, stream2;
std::string stringednumber;
int tempnumber;
stream1 << value;
stream1 >> tempnumber;
stream2 << tempnumber;
stream2 >> stringednumber;
if (!value.compare(stringednumber)) {
*result = tempnumber;
return true;
}
else return false;
}
코드를 올바르게 쓰면 문자열이 유효한 숫자인지 아닌지를 나타내는 부울 값이 반환됩니다.false일 경우 숫자가 아닙니다.true가 숫자이고 현재 결과일 경우 다음과 같이 호출합니다.
std::string input;
std::cin >> input;
bool worked = string_to_int(input, &result);
사용할 수 있습니다.std::stringstream예를 들어 다음과 같습니다.
#include <iostream>
#include <sstream>
using namespace std;
string r;
int main() {
cin >> r;
stringstream tmp(r);
int s;
tmp >> s;
cout << s;
return 0;
}
마이코드:
#include <iostream>
using namespace std;
int main()
{
string s="32"; //String
int n=stoi(s); //Convert to int
cout << n + 1 << endl;
return 0;
}
문자열 표현에서 정수 값으로 변환하려면 std:: stringstream을 사용합니다.
변환된 값이 정수 데이터 유형의 범위를 벗어나면 INT_MIN 또는 INT_MAX가 반환됩니다.
또한 문자열 값을 유효한 int 데이터 유형으로 나타낼 수 없는 경우 0이 반환됩니다.
#include
#include
#include
int main() {
std::string x = "50";
int y;
std::istringstream(x) >> y;
std::cout << y << '\n';
return 0;
}
출력: 50
위의 출력과 같이 문자열 번호에서 정수 번호로 변환된 것을 알 수 있습니다.
오류 처리가 완료되지 않았습니다.
int myatoti(string ip)
{
int ret = 0;
int sign = 1;
if (ip[0] == '-')
{
ip.erase(0, 1);
sign = -1;
}
int p = 0;
for (auto it = ip.rbegin(); it != ip.rend(); it++)
{
int val = *it - 48;
int hun = 1;
for (int k = 0; k < p; k++)
{
hun *= 10;
}
ret += val * hun;
p++;
}
return ret * sign;
}
송신원:
// stoi example
#include <iostream> // std::cout
#include <string> // std::string, std::stoi
int main ()
{
std::string str_dec = "2001, A Space Odyssey";
std::string str_hex = "40c3";
std::string str_bin = "-10010110001";
std::string str_auto = "0x7f";
std::string::size_type sz; // Alias of size_t
int i_dec = std::stoi (str_dec,&sz);
int i_hex = std::stoi (str_hex,nullptr,16);
int i_bin = std::stoi (str_bin,nullptr,2);
int i_auto = std::stoi (str_auto,nullptr,0);
std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
std::cout << str_hex << ": " << i_hex << '\n';
std::cout << str_bin << ": " << i_bin << '\n';
std::cout << str_auto << ": " << i_auto << '\n';
return 0;
}
출력:
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
long long toll(string a) {
long long ret = 0;
bool minus = false;
for (auto i : a) {
if (i == '-') {
minus = true;
continue;
}
ret *= 10;
ret += i-'0';
}
if (minus)
ret *= -1;
return ret;
}
사용방법:
long long a = toll(string("-1234"));
int stringToInt(std::string value) {
if (value.length() == 0 || value.find(std::string("NULL")) != std::string::npos || value.find(std::string("null")) != std::string::npos) {
return 0;
}
int i;
std::stringstream stream1;
stream1.clear();
stream1.str(value);
stream1 >> i;
return i;
}
atoi 는 문자열을 정수 표현으로 시작하는 것을 전제로 문자열을 정수로 변환하는 내장 함수입니다.
또 다른 쉬운 방법이 있다: 당신이 다음과 같은 캐릭터를 가지고 있다고 가정해 보자.c='4'따라서 다음 절차 중 하나를 수행할 수 있습니다.
첫 번째 : int q
q=(int) c ; (q is now 52 in ascii table ) . q=q-48; remember that adding 48 to digits is their ascii code .
두 번째 방법:
q=c-'0'; the same , character '0' means 48
한 줄 버전:long n = strtol(s.c_str(), NULL, base);.
(s문자열입니다.base는 입니다.int예를 들어 2, 8, 10, 16).
에 대한 자세한 내용은 이 링크를 참조하십시오.strtol.
핵심 아이디어는 에 포함된 기능을 사용하는 것입니다.cstdlib.
부터strtol취급만 하다char어레이, 변환이 필요합니다.string로.char어레이. 이 링크를 참조할 수 있습니다.
예:
#include <iostream>
#include <string> // string type
#include <bitset> // bitset type used in the output
int main(){
s = "1111000001011010";
long t = strtol(s.c_str(), NULL, 2); // 2 is the base which parse the string
cout << s << endl;
cout << t << endl;
cout << hex << t << endl;
cout << bitset<16> (t) << endl;
return 0;
}
출력:
1111000001011010
61530
f05a
1111000001011010
제 생각엔 그 변환이int로.std::string또는 그 반대의 경우도, 다음과 같은 특별한 기능이 필요합니다.std::stoi()하지만, 만약 당신이 변환해야 한다면double에string사용하다to_string()(C#이 아닙니다.C#은 입니다.ToString() not_string()
하드 코드를 사용하는 경우:)
bool strCanBeInt(std::string string){
for (char n : string) {
if (n != '0' && n != '1' && n != '2' && n != '3' && n != '4' && n != '5'
&& n != '6' && n != '7' && n != '8' && n != '9') {
return false;
}
}
return true;
}
int strToInt(std::string string) {
int integer = 0;
int numInt;
for (char n : string) {
if(n == '0') numInt = 0;
if(n == '1') numInt = 1;
if(n == '2') numInt = 2;
if(n == '3') numInt = 3;
if(n == '4') numInt = 4;
if(n == '5') numInt = 5;
if(n == '6') numInt = 6;
if(n == '7') numInt = 7;
if(n == '8') numInt = 8;
if(n == '9') numInt = 9;
if (integer){
integer *= 10;
}
integer += numInt;
}
return integer;
}
언급URL : https://stackoverflow.com/questions/7663709/how-can-i-convert-a-stdstring-to-int
'source' 카테고리의 다른 글
| 아이폰 네비게이션바 제목 텍스트 색상 (0) | 2023.04.17 |
|---|---|
| [NSObject description]의 Swift는 무엇입니까? (0) | 2023.04.17 |
| Swift - 방향 변화를 감지하는 방법 (0) | 2023.04.17 |
| 셀 색상을 얻기 위한 Excel 공식 (0) | 2023.04.17 |
| UITableView, 설정 장소 구분 색상 (0) | 2023.04.17 |