KryX
KryX

Reputation: 9

Why is my calculation with modulus giving me boxes?

Current input and output with code below:

Expected output:

When I compile and run the program and enter specifically a 4 digit number test such as "9876", my answer is literally 4 boxes. The answer should be 3197 but I don't really know what to do. I think there is a problem with the data types but I'm really unsure about how to fix this.

Input data:

9876

Output data:

????

Expected data:

3197

Here is my code so far:

#include <iostream> //access input output related code
#include <string>
#include <math.h>
#include <sstream>
#include <ctype.h>
#include <iomanip>
using namespace std; // use the C++ standard namespace which includes cin and
                     // cout

int main() {
  string encodednumber, decodednumber;
  int temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8;
  char initialnumber[10];

  cout << "Please enter a number: " << endl;
  cin.getline(initialnumber, 10);
  string str = initialnumber;
  int numlength = str.length();
  cout << "Number contains " << numlength << " digits" << endl;

  switch (numlength) {
  case 4:
    temp1 = initialnumber[0];
    initialnumber[0] = ((temp1 + 4) % 10);
    temp2 = initialnumber[1];
    initialnumber[1] = ((temp2 + 3) % 10);
    temp3 = initialnumber[2];
    initialnumber[2] = ((temp3 + 2) % 10);
    temp4 = initialnumber[3];
    initialnumber[3] = ((temp4 + 1) % 10);
    encodednumber = initialnumber;
    cout << "\nThe encoded number is " << encodednumber << endl;
    break;
  default:
    cout << "Not a valid input, re enter the number" << endl;
  }
  return 0;
}

Upvotes: 0

Views: 79

Answers (1)

john
john

Reputation: 88017

You're right, it's the data types. You're ignoring the difference between a char and an int and assuming that you can automatically convert between them.

To convert a digit character to the corresponding integer you must subtract '0'

temp1 = initialnumber[0] - '0';

To convert an integer to a char it's the opposite you must add '0'.

initialnumber[0] = ((temp1 + 4) % 10) + '0';

All characters are encoded as integers. The digits '0' to '9' are guaranteed to be a encoded by consecutive integers (with '0' having the lowest value). So subtracting '0' from a character converts the encoded value to the corresponding integer value.

Upvotes: 7

Related Questions