我正在尝试将字符串转换为 uint64_t 整数。 stoi
返回一个32位整数,所以在我的情况下无法使用。是否有其他解决方案?
如果你正在使用C++11或更高版本,请尝试使用std::stoull
。
这篇帖子也可能会有所帮助。我没有将其标记为重复,因为另一个问题是关于C的。
试试这个:
#include <iostream>
#include <sstream>
#include <cstdint>
int main() {
uint64_t value;
std::istringstream iss("18446744073709551610");
iss >> value;
std::cout << value;
}
请查看实时演示
这也可能适用于过时的标准。
std::istringstream
将返回0。std::stoull
会抛出一个std::invalid_argument
异常:现场演示。 - davidvandebunteiss >> value
返回的流与 true
相比较来检查提取是否成功,或者你可以通过 iss.exceptions(std::ios::failbit | std::ios::badbit)
在流上启用异常。 - Darklighter如果您使用的是C++11或更高版本,可以使用 <cstdlib> 中的 strtoull() 函数。
否则,如果您需要在 C99 中使用,可以选择来自 C 的 stdlib.h 中的 strtoull() 函数。
请看以下示例:
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
std::string value= "14443434343434343434";
uint64_t a;
char* end;
a= strtoull( value.c_str(), &end,10 );
std::cout << "UInt64: " << a << "\n";
}
所有这些解决方案都不符合我的需求。
所以我只是使用了一个 for 循环:
uint64_t val = 0;
for (auto ch: new_str) {
if (not isdigit(ch)) return 0;
val = 10 * val + (ch - '0');
}
#include <iostream>
#include <string>
#include <boost-1_61/boost/lexical_cast.hpp> //I've multiple versions of boost installed, so this path may be different for you
int main()
{
using boost::lexical_cast;
using namespace std;
const string s("2424242");
uint64_t num = lexical_cast<uint64_t>(s);
cout << num << endl;
return 0;
}
lexical_cast
_ 在这里如何变得有用呢? - πάντα ῥεῖboost::lexical_cast
非常容易使用,并且(至少根据他们自己的基准测试,最新的数字与gcc6.1一起测量),比stringstream
和scanf
+朋友们(用于手头的转换)要快得多。因此,如果您已经在使用boost,则这是进行此转换的好方法。 - Baum mit Augen.c_str()
,你可以直接使用std::string
。这样可能也更快。 - Baum mit Augenuint64_t stringToUint_64(String value) {
int stringLenght = value.length();
uint64_t uint64Value = 0x0;
for(int i = 0; i<=stringLenght-1; i++) {
char charValue = value.charAt(i);
uint64Value = 0x10 * uint64Value;
uint64Value += stringToHexInt(charValue);
}
return uint64Value;
}
int stringToHexInt(char value) {
switch(value) {
case '0':
return 0;
break;
case '1':
return 0x1;
break;
case '2':
return 0x2;
break;
case '3':
return 0x3;
break;
case '4':
return 0x4;
break;
case '5':
return 0x5;
break;
case '6':
return 0x6;
break;
case '7':
return 0x7;
break;
case '8':
return 0x8;
break;
case '9':
return 0x9;
break;
case 'A':
case 'a':
return 0xA;
break;
case 'B':
case 'b':
return 0xB;
break;
case 'C':
case 'c':
return 0xC;
break;
case 'D':
case 'd':
return 0xD;
break;
case 'E':
case 'e':
return 0xE;
break;
case 'F':
case 'f':
return 0xF;
break;
}
}