converting string starting with zero to int

My overall goal in this was to convert binary strings to integers, but now i am interested in also learning stringstream.

After looking around i found the method stringstream to be best?

The only problem i found when i was trying to use it to convert binary strings to ints was it stripped the initial 0, if it had one. Now this makes sense on average use, but what if you were using it to convert binary strings to ints?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream> 
using namespace std;

int main(){
	string stringer = "01100110";
	stringstream ss(stringer); 
	int i;
	ss >> i;
	cout << i + 1<< endl; 

	int inter = 123;
	stringstream num_str;
	num_str << inter;
	cout << num_str.str() + "test" <<endl; 

}
Last edited on
to be honest i was looking for a standard way for (int into str and str to int. ) I was looking at not to confuse myself as i just returned to c++ from python. I'm surprised at how hard it is to do basic things that in python i didnt even think of.

so in essence, i was looking for the same method to convert to and from, whereas atoi or itoa, ummm one of them is not in the standard library of C++.
metulburr wrote:
The only problem i found when i was trying to use it to convert binary strings to ints was it stripped the initial 0, if it had one.

That's simply a matter of how the output is formatted. By choosing the width and fill character, the number can be displayed as you wish:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

int main(){
    string stringer = "01100110";
    stringstream ss(stringer);
    int i;
    ss >> i;
    cout << setw(8) << setfill('0') << i << endl;
}

Output:
01100110
but what if you were using it to convert binary strings to ints?

Well, the above is an output issue. The input is not affected, hence it will work correctly.

As already suggested, strtol() is a standard way to convert a string to an integer, using any base from 2 to 36.

For amusement purposes, one of many, many ways to convert an int to a binary string:
1
2
3
4
5
6
7
8
9
std::string bin(unsigned int n)
{
    static const std::string digits[2] = {"0", "1"};

    if (n>>1)
        return bin(n>>1) + digits[n&1];
    else
        return digits[n&1];
}

Last edited on
Topic archived. No new replies allowed.