gpt4 book ai didi

c++ - 将 setfill 和 setw 的输出存储到字符串

转载 作者:太空狗 更新时间:2023-10-29 21:19:22 25 4
gpt4 key购买 nike

我正在尝试使用 C 的 itoa 函数和 C++ setfillsetw 函数生成二进制数。如果我只使用 itoa,则显示的输出没有正确的 0 填充。

这是一个小代码片段。

int s = 8;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
cout<<setfill('0')<<setw(3)<<endl;
cout<<buffer<<endl;
}

现在它在打印输出方面做得很好。

如果我没有使用 setfill 和 setw,格式会是这样的

1
10
11
100
101
110
111

代替

001
010
011
100
101
110
111

现在我想存储生成的填充二进制数并将其存储到一个 vector 中。可能吗?

我想我有一个使用 bitset 的解决方案,而且效果很好。

    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;

};

不过,我只想指出,我得到的解决方案看起来有些像这个! Bin

能否通过在连续迭代中刷新流来操纵它。这只是事后的想法。

最佳答案

考虑使用 bitset 而不是 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());
}
}

编辑:如果您需要可变长度,一种可能性是

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

后来

binary_representations.push_back(binary_string(i, 3));

关于c++ - 将 setfill 和 setw 的输出存储到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27620849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com