将setfill和setw的输出存储到字符串 我试图用C的 ITOA函数和C++ SETPAST/和 SEtW商店< /代码>函数来生成二进制数。如果仅使用itoa,则显示的输出没有正确的0填充
这是一个小代码段将setfill和setw的输出存储到字符串 我试图用C的 ITOA函数和C++ SETPAST/和 SEtW商店< /代码>函数来生成二进制数。如果仅使用itoa,则显示的输出没有正确的0填充,c++,string,C++,String,这是一个小代码段 int s = 8; for (int i = 1; i<s;i++) { itoa(i,buffer,2); cout<<setfill('0')<<setw(3)<<endl; cout<<buffer<<endl; } 而不是 001 010 011 100 101 110 111 现在我想存储生成的填充二进制数,并将其存储到向量中。可能吗
int s = 8;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
cout<<setfill('0')<<setw(3)<<endl;
cout<<buffer<<endl;
}
而不是
001
010
011
100
101
110
111
现在我想存储生成的填充二进制数,并将其存储到向量中。可能吗
我想我已经找到了一个使用位集的解决方案,而且效果很好
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;
};
std::ostringstream oss;
int s=3;
对于(int i=1;i考虑使用位集而不是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());
}
}
您正在寻找吗?好的,在c99
标准中没有itoa()
。可能您正在使用支持此函数的编译器扩展。是的,谢谢您的回复,它可以工作,但是您想知道我为什么不应该使用itoa吗。主要是因为它更简单(它已经完全满足您的需要)一般来说,最好避免在C++中使用C风格字符串,除非你有很好的理由使用它们,因为它很容易出错,缓冲区可能太短,你可以忘记零终止符(谢谢,<代码> SNPRTNF < /代码>!)你可以忘记<代码>免费< /Cord>什么是<代码> StuppU/<代码>,那是一种类型的东西。如果你使用的是等价的C++构造,那么这些错误就更难做了。哦,和<代码> ITOA特别不太便携(我在Linux上没有它)。对不起,稍后才意识到,位集中的3代表什么?是2^3=8吗?而且3也可以被变量替换吗?谢谢。这意味着位集中有三位。所以…是的,实际上,但我建议使用它的原因是位集的字符串表示形式是N
字符长的,而不管大小它所代表的数字。我想这和用不同的方式说的是一样的。我想像这样使用它:int x=4;bitset(1)。to_string()。有可能吗。Visual Studio说bitset<>只接受常量,不接受变量。
#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));