Erik Vesterlund
Erik Vesterlund

Reputation: 448

C++ Looping with String Functions

I'm doodling with this implementation of SHA-256. I'm trying to write a program that produces sha(0), sha(1), ... but I'm unable to. Naively I tried

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

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

Of course, this doesn't produce sha256(0), sha256(1), ..., but rather interprets the i as the letter i, and not the integer variable i. Any advice on how to remedy this? Altering the function implentation itself is not feasible so I'm looking for another way. Clearly I don't know much C++ at all, but any advice would be much appreciated.

EDIT:

#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;

Upvotes: 2

Views: 115

Answers (1)

vsoftco
vsoftco

Reputation: 56577

You need to transform the number i to the string i accepted by SHA. A straightforward option is to use the std::to_string C++11 function

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

In case you don't have access to a C++11 compiler (you should have, it's almost 2016), you can glance at this excellent link:

Easiest way to convert int to string in C++

Quick (not the most efficient) way of doing it with a 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; 
    }
}

Upvotes: 4

Related Questions