试图更多地了解 C++ 中的位集

Trying to understand more about bitset in c++

我试图了解更多有关使用 bitset 将字符串转换为二进制然后将其转换为另一个字符串而不是直接 cout 的信息。我将始终收到异常错误“0x773D3DB2 C++ 异常未处理的异常:std::invalid_argument 在内存位置 0x006FF800。 " 使用 visual studio 2017 我可以知道为什么吗?

#include <string>
#include <bitset>
#include <sstream>
#include <iostream>

using namespace std;



int main()
{

   std::string hello = "C";
   std::string yellow;
   for (auto character : hello)
   {
    yellow += std::bitset<7>(hello).to_string();
    cout << yellow;
    return 0;
   }

}

您的编译器没有启用警告,或者使用的编译器无法警告您变量 character 未在您的循环中使用。

改变

yellow += std::bitset<7>(hello).to_string();

yellow += std::bitset<7>(character).to_string();

输出:

1000011

另外,请注意您实际上并没有 循环 ,因为您的循环 return 是在第一次迭代时。我假设您的代码示例此时已经经历了多次反复试验和错误...