我正在用 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;
最佳答案
您需要将数字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;
}
}
关于使用字符串函数进行 C++ 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663828/