Reputation: 1680
I am trying to produce binary numbers using C's itoa
function and C++ setfill
and setw
function. If I use only itoa
, the output displayed does not have proper 0
padding.
This is a small code snippet.
int s = 8;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
cout<<setfill('0')<<setw(3)<<endl;
cout<<buffer<<endl;
}
Now it does a great job in printing out the output.
If I hadn't used setfill and setw, the formatting would have been something like
1
10
11
100
101
110
111
instead of
001
010
011
100
101
110
111
Now I want to store the padded binary numbers produced and store it into a vector. Is it possible?
I think I have got a solution using bitset, and it works fine.
std::ostringstream oss;
int s = 3;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
oss<<setfill('0')<<setw(3);
oss<<buffer;
string s = oss.str();
cout<<s<<'\n'<<endl;
};
However, I just want to point out that the solution I obtained looks some this!
Can it manipulated by flushing out streams in consecutive iterations. Its just an afterthought.
Upvotes: 3
Views: 1593
Reputation: 44043
Consider using a bitset
instead of itoa
:
#include <bitset>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> binary_representations;
int s = 8;
for (int i = 1; i < s; i++)
{
binary_representations.push_back(std::bitset<3>(i).to_string());
}
}
EDIT: If you need a variable length, one possibility is
// Note: it might be better to make x unsigned here.
// What do you expect to happen if x < 0?
std::string binary_string(int x, std::size_t len) {
std::string result(len, '0');
for(std::string::reverse_iterator i = result.rbegin(); i != result.rend(); ++i) {
*i = x % 2 + '0';
x /= 2;
}
return result;
}
and then later
binary_representations.push_back(binary_string(i, 3));
Upvotes: 3