c++哈希字符串X次,然后写入控制台

C++ hash string X number of times and then write to console

本文关键字:然后 控制台 哈希 字符串 c++      更新时间:2023-10-16

在我开始之前,我想说的是,当谈到c++时,我是一个完全的初学者,但我熟悉其他编程语言。

我正在尝试写一个代码,将一个字符串,并哈希它X次。

伪代码:

Times to hash = X
String to hash = "Hello world"
For i=1 to 10
   hash string
next
Console write string that has been hashed X times.

我做了一些研究,我修改了这个代码,但问题是哈希算法是md5,我希望它是sha256(但我找不到一个有用的代码,我可以适应)

#include "md5.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
  MD5 md5 ;
  string str1(md5.digestString( "String" ));
  cout << str1;
  return 0;
}

我已经看了几个for循环,但我似乎可以让他们中的任何一个工作,但这里是我的尝试之一:

int i = 0;
for (; i<50; ++i) {
    cout << "Hello world";
}

for循环的错误:

2   1   C:Users9stephenbDesktopHash.cpp    [Error] expected unqualified-id before 'for'
2   8   C:Users9stephenbDesktopHash.cpp    [Error] 'i' does not name a type
2   14  C:Users9stephenbDesktopHash.cpp    [Error] expected unqualified-id before '++' token

但我得到错误,如&;它不是一个类型&;,我假设变量类型,但我不太确定下一步该怎么做。

我现在有点不愿意完全学习c++,因为这只是我正在从事的项目的一小部分。

编辑

形成评论和答案,我有这个代码:

#include <iostream>
#include "md5.h"
#include <string>
using namespace std;
int main() {
    int count = 50;
    std::string prev = "stringtohash";
    std::string cur;
    
    for(int i=0; i < count; ++i) {
        cur = md5.digestString(prev);
        prev = cur;
    }
    
    std::cout << cur;
    return 0;
}

但是它返回错误:[Error] 'md5' was not declared in this scope

循环可以是这样的:

for (int i = 0; i<50; i++) {
     cout << "Hello world"
}

sha256检查http://www.cryptlib.com/

添加了"<<"操作符,如Fabio Turati所说。

几乎和你的伪代码一样:)

int count = 50;
std::string cur = "stringtohash";
for(int i=0; i < count; ++i) {
    cur = whateverlib.md5.digest(cur );
}
std::cout << cur;