Question

Having an issue inputting an ACTUAL string to strtuol. The input string SHOULD be an unsigned binary value of 32 bits long.

Obviously, there is in issue with InputString = apple; but I'm not sure how to resolve the issue. any thoughts? This shouldnt be that difficult. not sure why I'm having such a hard time with it.

Thanks guys.

#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;
}
Was it helpful?

Solution 2

Include :

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

and then

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

Or simply,

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

OTHER TIPS

A better approach would be to avoid the legacy-C functions and use the C++ standard functions:

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

NOTE: std::stoull will actually call ::strtoull internally, but it allows you to just deal with the std::string object instead of having to convert it to a C-style string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top