user2225891
user2225891

Reputation:

using array elements to perform calculations

I am trying to create a hashing function. The algorithm requires me to take each letter of the string and convert it to ASCII; multiply it by a number based on its position in the string (for example Input is STACK; ASCII for 'S' would be 344, multiply that value by 9^9 then ASCII for 'T' would be 347 multiply that value by 8^8.. etc); and then add the values together.

I understand how to access the values in the array to create the sum and can convert them to ASCII. I don't understand how I would access the array to perform the calculations in-between.

I also get an "assertion failed error", when I build the program. I looked up the error and it says it has something to do with bad calls, however I can't see any bad calls in my code.

my code is below :

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input ;
    int finalanswer = 0;

    cout << "Enter your first name please : " ;

    cin >> input;

    cout << "Your name is " << input ;

    for (int x=0; x=input.size(); x++)
    {   
        finalanswer += input[x];

        cout << finalanswer ;
    }

    cin.get();
    return 0;
}

Upvotes: 0

Views: 167

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56883

The condition in the for-loop is wrong, it should be

for(int x=0; x < input.size(); x++)

With your code, the second time the body of the loop is executed x is input.size() and that is too large to access input[x] - leading to the error you see.


I'm not sure I understand the intended algorithm 100%, but that might help:

int myPow(int x, int p)
{
  if (p == 0) return 1;
  if (p == 1) return x;
  return x * myPow(x, p-1);
}

and then for the loop:

for(int x=0; x < input.size(); x++)
{
    finalanswer += input[x] * myPow(9-x);

    cout << finalanswer ;
}

Upvotes: 2

Related Questions