简体   繁体   English

将setfill和setw的输出存储到字符串中

[英]Storing output from setfill and setw to a string

I am trying to produce binary numbers using C's itoa function and C++ setfill and setw function. 我试图使用C的itoa函数和C ++ setfillsetw函数生成二进制数。 If I use only itoa , the output displayed does not have proper 0 padding. 如果我只使用itoa ,则显示的输出没有正确的0填充。

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 如果我没有使用setfill和setw,格式就会像

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. 我想我有一个使用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;

    };

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. 它只是一个事后的想法。

Consider using a bitset instead of itoa : 考虑使用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());
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM