如何做真正的斯特图尔?不会引入实际字符串

How to do a true strtoul? Wont intake an actual string

本文关键字:字符串 何做真      更新时间:2023-10-16

向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;
}

更好的方法是避免使用legacy-C函数并使用C++标准函数:

string apple = "11111111110000000000101010101000";
unsigned long long x = std::stoull(apple, NULL, 2); // defined in <string>

注意:std::stoull实际上会在内部调用::strtoull,但它允许您只处理std::string对象,而不必将其转换为 C 样式字符串。

包括:

#include<cstdlib> // for strtol()
#include<cstring> // for strncpy()

然后

 strncpy(InputString ,apple.c_str(),40); 
                            ^
                            |
                            convert to C ctring 

或者简单地说,

unsigned long x = strtoul(apple.c_str(), &pEnd, 2);