【问题标题】:C++ Looping with String Functions带有字符串函数的 C++ 循环
【发布时间】:2015-11-12 12:56:35
【问题描述】:

我正在涂鸦this SHA-256 的实现。我正在尝试编写一个产生 sha(0)、sha(1)、...的程序,但我做不到。我天真地尝试过

#include <iostream>
#include "sha256.h"

int main(int argc, char *argv[]){ 
   for (int i=0; i < 4; i++)
      std::cout << sha256("i");
   return 0;
}

当然,这不会产生 sha256(0), sha256(1), ...,而是将 i 解释为字母 i,而不是整数变量 i。关于如何解决这个问题的任何建议?改变功能实现本身是不可行的,所以我正在寻找另一种方法。显然我对 C++ 了解不多,但任何建议都将不胜感激。

编辑:

#include <iostream>
#include "sha256.h"
#include <sstream>

int main(int argc, char *argv[])
{
std::cout << "This is sha256("0"): \n" << sha256("0") << std::endl;
std::cout << "Loop: " << std::endl;
std::stringstream ss;
std::string result;
for (int i=0; i < 4; ++i)
{
    ss << i;
    ss >> result;
    std::cout << sha256(result) << std::endl;
}
return 0;

【问题讨论】:

  • sha256("i")更改为sha256(i)
  • @underscore 不是真的,因为 SHA 需要一个字符串。

标签: c++ string for-loop hash


【解决方案1】:

您需要将数字i 转换为SHA 接受的字符串i。一个直接的选择是使用std::to_string C++11 函数

std::cout << sha256(std::to_string(i)); 

如果您无法访问 C++11 编译器(您应该拥有,现在已经是 2016 年了),您可以看看这个出色的链接:

Easiest way to convert int to string in C++

使用std::stringstream 快速(不是最有效)的方式:

#include <iostream>
#include <sstream>
#include "sha256.h"

int main()
{
    std::string result;
    std::stringstream ss;
    for (int i = 0; i < 4; i++)
    {
        ss << i;
        ss >> result;
        ss.clear(); // need to clear the eof flag so we can reuse it
        std::cout << sha256(result) << std::endl; 
    }
}

【讨论】:

  • 谢谢!我想现在我要做的就是修复“to_string 不是 std 的成员”故障,嗯...
  • @ErikVesterlund 如果您使用 gcc,请确保使用 -std=c++11 进行编译以启用 C++11 支持。如果您没有 C++11 编译器,请使用我发布的链接中的转换方法。
  • 嗯,我在代码块中写东西,它使用 gcc 吗?我应该在哪里写?
  • 谢谢。我现在已经尝试了所有这些,但我无法让它工作。 to_string 同样的问题(甚至在编译器设置中选中相关框后重新启动代码块)并且 itoa 和 stringstream 也不起作用。
  • std::stringstreamitoa 肯定可以工作。确保 #include &lt;sstream&gt; 对应 std::stringstream#include &lt;cstdlib&gt; 对应 itoa。尽量避免itoa,因为它是非标准的。现场示例here.
猜你喜欢
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2011-07-24
  • 2012-04-07
  • 2022-01-26
  • 2013-11-08
  • 2019-08-12
相关资源
最近更新 更多