Problem with char arrays and switch statements

Mar 5, 2010 at 7:47pm
closed account (jwC5fSEw)
I'm having a problem with using char arrays. Here's the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    int getFormat(){
        while(true){
            cout << "What movie format would you like to rent?\n" <<
                    "1. VHS\n" <<
                    "2. DVD\n" <<
                    "3. Blu-ray\n";
            cin >> format;
            switch(format){
                case 1:
                    cout << "You have chosen to rent a VHS.\n";
                    formatChar = "VHS";
                    return 1;
                case 2:
                    cout << "You have chosen to rent a DVD.\n";
                    return 2;
                case 3:
                    cout << "You have chosen to rent a Blu-ray.\n";
                    return 3;
                default:
                    cout << "You have not selected a valid choice.\n";
                    break;
            }
        }
    }


I have formatChar declared as "char formatChar[15];" earlier in the struct. I want to set the array to the format selected before returning the number of the format. However, it returns an error:

C:\CodeBlocks\Exercises\Chapter 4\exercise4.13.cpp|34|error: incompatible types in assignment of `const char[4]' to `char[15]'|


I sort of understand what this means, but I don't know how to fix it. (Also, I know strings would probably be a better choice, but I'm using a book and it hasn't really taught strings yet so I want to stick to the basic data types.)
Mar 5, 2010 at 7:56pm
You can't just assign arrays. You have to copy their elements one by one. In the case of char arrays, there already exists a function to do that: strcpy(formatChar,"VHS");

This is the least annoying of the reasons why using std::string is encouraged. Just wait until you get to memory management.
Mar 5, 2010 at 7:58pm
Make it a string instead of a char array. They're better for a variety of reasons.

1
2
3
string formatChar;

formatChar = "whatever";


If you really want to use a char array for some reason, you have to copy the string with strcpy:

1
2
3
char formatChar[15];

strcpy(formatChar,"whatever");


EDIT: doh, too slow.
Last edited on Mar 5, 2010 at 7:58pm
Mar 5, 2010 at 8:01pm
closed account (jwC5fSEw)
Yeah, I can easily how strings are preferred over char arrays. However, it feels better to keep in the context of the book and wait until later to learn the easy way :D

Also, I love this forum. I haven't been on many forums about anything where the other members were so helpful and prompt in responding. Every single question I've asked on here has been answered well. It's really a great place.
Topic archived. No new replies allowed.