그냥 투명지에 신속시작 질문이예요 # 39, ve 인터넷을 중심으로 생각하고 i& 상당히 비트 및 I& # 39, 그들 중 아무도 일한 적이 몇 번 com/downloads/global/corporate/iar/esg_prosupport. 솔루션은 물론 아직 밝혀지지 않았다. 내가 볼 때, t 짓궂군요 ASCII 코드 변환 충족되었으며 int 문자열으로 don& # 39.
우리는 방정식에 대한 간략한 개요 문자열로 통과시켰다. 우리가 이 문제를 제대로 break it down, 형식 및 선형 방정식. # 39 m, 할 수 없는 것을 말하고, 이번에는 두 I& 문자열으로 변환하시겠습니까 충족되었으며 int.
구체화하십시오 될 것으로 알고 있는 형식 (5) 또는 (25) 등 그러하매 it& # 39 의 말해둘꼐요 하지만 어떻게 문자열으로? 에서 푸십시오 충족되었으며 int.
제 생각에 대해 한 가지 방법은 실행하는지 / while 루프를 통해 모든 자리 숫자가 확인할지 구체화하십시오, 그 후, 추출 후 주요 & # 39, & # 39 - look to see if there was a int 가 있는 경우, 곱합니다, - 1.
이러한 복잡한 문제를 조금 넘는 작은 어쨌든요 보인다 아무 생각 없어?
C++11 에서 몇 가지 새로운 기능이 좋은 변환하십시오 표준용량 구체화하십시오 '에서' 여러 유형:.
그래서 대신
atoi( str.c_str() )
사용할 수 있습니다.
std::stoi( str )
여기서 '할 수 있다' 는 '네' 표준용량 구체화하십시오 str.
모든 변종에서 가지 버전 번호: '긴 단거리 이착륙기 (string)', '부동 소수점 스토프 (string)', '더블 스트로트 (string)'. 참조 http://en.cppreference.com/w/cpp/string/basic_string/stol
가능한 옵션 다음과 같습니다.
1. 첫 번째 옵션은: 스카노프 ()
#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
이 때문에, 스칸프 는 오류 (또한 표시하는 치피치크) 의 큰 충돌 없이 너버 제한값 " 필드이므로 수 있는 입력 데이터를 일부 버전의 libc", 자세한 내용은 here 및 여기서요).
2. 두 번째 옵션은: 표준용량 sto () *
#include <iostream>
#include <string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(s);
// string -> float
float f = std::stof(s);
// string -> double
double d = std::stod(s);
} 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 ??
그러나 이 솔루션을 통해 구별하기 힘든 나쁜거라 입력입니다 (http://otl. here).
4. 네 번째 옵션은: # 39 의 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
}
그러나 이는 단지 래퍼, 보다 나은 오류 관리 및 documentation 제안됩니다 스트림 스트럼 사용할 수 있다 (자세한 내용은 here).
5. 5 옵션: 스트라토 () *
이 솔루션은 오류로 인한 관리, 이는 매우 긴, 설명됨 삽입하십시오. 일반 없으므로 함수는 (int, 변환 요구되는가) 의 경우, 정수 (http://otl. here 이 변환 방식에 대해 달성할 수 있다).
6. 6 옵션: Qt
#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++11 총정리한, 최적의 솔루션이라는 표준용량 스토리 () 또는, 그 두 번째 옵션은 사용, qt 라이브러리를. 다른 모든 솔루션은 언제나 또는 갈레라 컴퍼니.
무슨 얘기 [Boost.Lexical_cast] (http://www.boost.org/doc/libs/release/doc/html/boost_lexical_cast.html)?
다음은 그 예:
>. 다음 예제에서는) 에서는 명령행을 인수만 시퀀스로 숫자 데이터:
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);
}
}
...
}
알듯, 나의 모든 것, t # 39 wouldn& 솔루션을 사용할 수 있는 텍스트를 입력으로부터 양의 정수를 대응시키는 푸십시오 제외어 정수, 기초적 성질. It '사용' 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
(테스트링) ',' boost::lexical_cast< int> 작업에 대한 합니다. 아주 잘.
Http://www.cplusplus.com/reference/string/stoi/ 에서
// 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년 스페이스 오디세이: 2001년, [, 스페이스 오디세이]
40c3: 16579
0x7f: 127
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";
}
'기본' 해석 ',' 스트라이스트림 스트라토르 지정해야 할 필요가 있는 경우 에스데키멀.
뭐, 많은 답변, 많은 가능성. 내가 다른 c++컴파일러는 변환하는 방법을 누각되었습니다 슬라이드에서는 일부 통합 문자열으로 핵심 유형 (파선-짧은, int, long, 부울.). I came up with 정보정의다음 해결책:
#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
스트라이스트림 출력입니다 변환할지 연산자입니다 문자열으로 중요한 유형) 에 사용하는 것은 어떻습니까? 다음은 대답:
이제 변환할 때 구체화하십시오 충족되었으며 int:
stringstream ss(str);
int x;
ss >> x;
2147483647, x 가 지정하십시오. 말해둘꼐요 오류가 발생했습니다. 문자열이어야 " ". 2147483648. int (2147483647) 로 변환하지는 돼 있지 않았다. 이러한 오류는 투안테그라티파 제공된 함수은 별색에 외친 뒤 예외가 아니다.
한 줄로 버전: '긴 n = 스트라토르 (s.c_str (), NULL, 베이스),'.
('s' 는 문자열, '기본' 은 'int' 등 2, 8, 10, 16.)
[이 링크] 참조할 수 있습니다 (https://stackoverflow.com/a/14794138/8328786) 에 대한 자세한 내용은 '스트라토르'.
핵심 사용할 수 있다는 ['스트라토르'] (http://www.cplusplus.com/reference/cstdlib/strtol/) ',' 코스타드리브 함수은 포함되어 있음.
이후 스트라토르 '만' 을 (를) ',' 문자열 처리 '를' 필요하다 '어레이입니다 챨 변환하십시오 챨' 어레이입니다. [이 링크] 참조할 수 있습니다 (https://stackoverflow.com/a/13294114/8328786).
예:
#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