0

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;
}
cmonnats23
  • 15
  • 1
  • 6
  • Can you use [`std::stoul`](http://en.cppreference.com/w/cpp/string/basic_string/stoul) instead? It takes a `std::string` directly. – Blastfurnace Oct 03 '13 at 16:45
  • Um, the input string should be a sequence of 32 **characters**, each being `1` or `0`. The string does not have a numeric value. – Pete Becker Oct 03 '13 at 16:55

2 Answers2

1

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.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • I agree with this answer but `std::stoul` is a better match for the example code in the question. – Blastfurnace Oct 03 '13 at 17:24
  • @Blastfurnace If his string was 32 characters long, I would agree. Since it is 33 characters long (and his current C-style string is 40 characters), a 64-bit version of the function is a better match. They are in the same family of functions, however (and both are declared in ``. – Zac Howland Oct 03 '13 at 18:01
0

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);

P0W
  • 46,614
  • 9
  • 72
  • 119
  • Shouldn't you use strncpy to avoid buffer overflow? For that matter, why copy the string at all; why not use apple.c_str() directly in strtoul()? – Cookyt Oct 03 '13 at 16:45
  • Works perfect. and elimintaes the need to use `inputstring` thanks guys. – cmonnats23 Oct 03 '13 at 16:49
  • @cmonnats23 - while `strncpy` avoids overflowing the buffer, if the input string is the same size as the buffer `strncpy` does **not** append a terminating nul character and you have a garbage string. – Pete Becker Oct 03 '13 at 16:58