0
int main() {

    char myarr[100];
    int arrlenght;

    cipher(myarr);
    decypher(myarr);
}

void cipher(char myarr[]) {


    cout << "Enter the chars you want to encrypt and enter '#' to stop " << endl;
    for (int i = 0; i < 100; i++) {

        cin >> myarr[i];
        if (myarr[i] != '#')
            continue;
        else
            break;
    }

    for (int j = 0; j < sizeof(myarr)/sizeof(myarr[0]); j++) {
        cout << static_cast<char>(myarr[j] + 3);
    }

}

void decypher(char myarr[]) {

    cout << "if you want to Decypher the sentence press '1' if you don't press '2' " << endl;
    int input;
    cin >> input;

    for (int i = 0; i < sizeof(myarr)/sizeof(myarr[0]); i++) {

        if (input == 1)
            cout << static_cast<char>(myarr[i]);
        else
            break;
    }


}

so this program is supposed to encrypt a word then decrypt it but the problem is it only encrypt and decrypts the 1st 4 chars only .. any idea as to why ?

i know where the error is but i just can't understand what to put in the for loop to fix it. i want a predefined function if there is any or another way to get me the array length after the user is done typing

Ahmed Hassan
  • 31
  • 2
  • 9
  • 1
    Please give us an [MCVE] – gsquaredxc Feb 26 '18 at 23:44
  • sizeof(myarr)/sizeof(myarr[0]) will probably return 4. You need to track array sizes manually in C, it's not stored with the array – Laserallan Feb 26 '18 at 23:46
  • It _is_ stored with the array (it's part of the type), but `decypher` doesn't receive an array, it receives a pointer. – Lightness Races in Orbit Feb 26 '18 at 23:48
  • @Laserallan how may i do that ? how may i track it manually it is up for the user how many chars will he enter – Ahmed Hassan Feb 26 '18 at 23:55
  • C is explicit about memory management and requires some effort. You will need malloc/free to allocate memory when reaching your buffer size and memcpy to copy what was already in your buffer to your new array. If learning C is the goal you should definitely go through the exercise of doing this right. If you just need to make something work, make the array big compared to the expected input size and pass it as a separate int to your cipher and decipher functions and if you hit it you exit with an error. If it's human input text on a PC 1MB is likely to be enough and not cause any trouble. – Laserallan Feb 27 '18 at 23:44

0 Answers0