How can I convert a const char * to a string?

I am getting an error saying I can't do this:

1
2
3
4
5
6
string * arr;
arr = new string[3];
arr[0] = "Play";
arr[1] = "Multiplayer";
arr[2] = "Options";
arr[3] = "Credits";
1
2
3
4
5
6
string * arr;
arr = new string[3];  // you're only allocating 3 strings
arr[0] = "Play";
arr[1] = "Multiplayer";
arr[2] = "Options";
arr[3] = "Credits";  // this 4th one is out of bounds 


Apart from that, what you're trying to do is legal. What is the exact error message you're getting?
That's right!
Oh, I think the real issue is what I had under it then.

UI testmenu(4, arr, "Hello and Welcome", "Just use W and S to navigate");

This is the constructor of a class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UI::UI(int Total_options, const string * menuwords, const string * Header, const string * Footer)
{
	menuarray = new string[Total_options];
        total_options=Total_options;
	
	for(int i=0; i<=total_options; i++)
	{
		menuarray[i] = menuwords[i];
	}
	header = *Header;
	footer = *Footer;

	place = 0;
	this->display();
}
Last edited on
Make your programming life a lot simpler.

1. Use std::vector<> instead of C-style arrays.
http://www.mochima.com/tutorials/vectors.html

2. Use value semantics for non-object-oriented types like std::string

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
#include <string>
#include <vector>

struct UI
{
    UI( const std::vector<std::string>& menuwords,
        const std::string& either_header_or_footer, bool is_header ) ;
        
    // ...    

    std::vector<std::string> menuarray ;
    std::string header_or_footer ;
    bool head ;
    bool foot ;
};

UI::UI( const std::vector<std::string>& menuwords,
        const std::string& either_header_or_footer, bool is_header )
                : menuarray(menuwords), header_or_footer(either_header_or_footer)
      { head = is_header ; foot = !is_header ; }

int main()
{
    std::vector<std::string> menuwords { "one", "two", "three", "four" } ;
    UI ui( menuwords, "this is a header", true ) ;
}
I will be sure to look those up.
AlitCandle: You're still stepping out of bounds:

1
2
3
4
5
6
7
	menuarray = new string[Total_options];
        total_options=Total_options;
	
	for(int i=0; i<=total_options; i++)  //  <=  is WRONG
	{
		menuarray[i] = menuwords[i];
	}


If you create an array of [4] elements... that means that [0], [1], [2], and [3] are valid. [4] is not valid and you cannot access it! Bad Bad Bad.
Topic archived. No new replies allowed.