将 ACTUAL 字符串输入到 strtuol 时出现问题。输入字符串应该是 32 位长的无符号二进制值。
显然,InputString = apple;
存在问题,但我不确定如何解决该问题。有什么想法吗?这不应该那么困难。不知道为什么我这么难过。
谢谢大家。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char InputString[40];
char *pEnd = NULL; // Required for strtol()
string apple = "11111111110000000000101010101000";
//cout << "Number? ";
//cin >> InputString;
InputString = apple;
unsigned long x = strtoul(InputString, &pEnd, 2); // String to long
cout << hex << x << endl;
return 1;
}
最佳答案
更好的方法是避免遗留 C 函数并使用 C++ 标准函数:
string apple = "11111111110000000000101010101000";
unsigned long long x = std::stoull(apple, NULL, 2); // defined in <string>
注意:std::stoull
实际上会在内部调用 ::strtoull
,但它允许您只处理 std::string
对象,而不必将其转换为 C 风格的字符串。
关于c++ - 如何做一个真正的strtoul?不会摄入实际的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19164549/