使用字符串函数进行 C++ 循环

标签 c++ string for-loop hash

我正在用 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/

相关文章:

c++ - 单击 View 中的项目时从另一个小部件访问自定义模型数据

javascript - 在 Javascript 中从字符串中提取一部分

python - 如何拆分字符串并转换为整数

Python 2 - "For counting loop"

c++ - std::list<std::reference_wrapper<T>> 的基于概念限制范围的 for 循环

头文件 c++11 中的 C++ 静态常量字符串

c++ - 类类型变量声明错误

使用外部函数的 C++ 模板

c# - 需要一些关于排序字符串列表的想法

PHP 为除最后一项以外的每一项添加逗号