I'm having trouble with my code

So I'm, trying to code a program that codes your message into a secret one. My problem in this code is that it crashes in the for loop. So the program asks you to type your message then it goes in the for loop. I want to cout "it works" to see if there is a bug or something and yes indeed there's one. Sorry, I'm still very new in programming. I will appreciate your help to locate my error and explain to me why this is happening. Thanks in advance!

(bad English sorry)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>

using namespace std;
//Declaring function
string codingmesseage();

int main()
{
    cout << "please type a message then press enter to code it into a secret one.\n";
    cout << "Type message here: ";
    codingmesseage();
}



string codingmesseage()
{
    char message[] = {};
    string codedmessage = "";

    cin >> message;

    for (unsigned int index = 0; index < sizeof(message); index++ )
    {
        cout << "it worked";
    }




return codedmessage;
}
Last edited on
Try defining your message as a string in line 18 instead (because you don't know how big it is going to be, and a string is a container, which can expand as necessary):
string message;

Although it would then "work" as is, I suggest you change your loop to
1
2
3
4
    for (int index = 0; index < message.size(); index++ )
    {
        cout << "it worked" << endl;
    }


Your cryptography will later replace line 25 in the loop.
Thanks for the help lastchance! Yeah, with a string I don't need to reserve space. I forgot about that. But now I'm facing another challenge! I want the for loop to go over each character in [code]string message[\code] in a switch statement. There will be a list of codes with that character.

for example:
[code]
switch(message)
{
case 'a': codedmessage = codedmessage + "JsDvdr9p"
break;

case 'b': codedmessage = codedmessage + "vK5PMXv7"
break;
//and so on
[\code]

With an array, I can point between brackets but not with strings. Do I use pointers or something?
Last edited on
No, you already have a loop set up to go through the characters of message one by one.
At the start, define
char c;

Within your loop (where you currently have cout << "it worked" << endl;):
1
2
3
c = message[index];
switch( c )
{

etc. as above. You are then "switch"ing on the individual characters.
ok thanks for all the help I appreciate it! Because of you, I finished my program and learned a little more.
Topic archived. No new replies allowed.