converting string to const char *

Dec 9, 2011 at 3:18pm
Hello,

I have three questions.

1 ) Say I have a string variable with three dates
string myDates[3] = {"11/12/2010","11/13/2010","11/14/2010"};

How do I figure out the number of dates?

2 ) If I will be reading the dates from a file, what is the best container for storing the dates if I don't now the number of dates in advance? Should I use vector<string> instead?

2 ) I need to create
const char *dates[3] = {"11/12/2010","11/13/2010","11/14/2010"};
from myDates, which is a string variable from question 1.
How can I do this?

I tried the following but it didn't work.
1
2
3
4
for (int i = 0; i < 3; i++)
{
      strcpy(dates[i],myDates[i].c_str());
}





Dec 9, 2011 at 4:08pm
Never mind guys.
The following works.

N = 3;
const char *tmp[N];
string myStrings[N] = {"11/12/2010","11/13/2010","11/18/2010"};
1
2
3
4
for (int i = 0; i < N ; i++)
{
    tmp[i] = myStrings[i].c_str();
}
Dec 9, 2011 at 4:08pm
For finding number of date .

1
2
3
4
5
6
   int count_date = 0; 
	while(! myDate[i].IsEmpty())
	{
		count_date++;
	};
	cout<<"\n Number of date = "<<count_date;


2) string array is ok for storing the date from the file .
3)

1
2
3
4
5
6
7
8
9
	       for( int i = 0 ; i < count_date; i++)
		{
			   dates[i] = new  char[myDate[i].length() +1];

		       strcpy( date[i] , myDate[i].c_str());
		}

		
		delete [] date ; 


Last edited on Dec 9, 2011 at 4:14pm
Dec 9, 2011 at 6:05pm
1
2
3
4
	while(! myDate[i].IsEmpty())
	{
		count_date++;
	};
¿so how is the condition modified in any way?

The container of choice will depend on the process that you want to do. By instance, if you want a dictionay you should use a std::set

¿why do you want the char* array for? Keep in mind that if you modify the strings, they may reallocate, so your pointers will be pointing at garbage.
In bluecoder's code the memory is leaking and there is a bad delete
Dec 10, 2011 at 11:39am
I mean to say string *dates[3] .

how do i delete the string pointer array .
Last edited on Dec 10, 2011 at 11:40am
Dec 10, 2011 at 4:24pm
You've got to delete what you newed.
dates[i] = new char[myDate[i].length() +1]; so later you need delete [] dates[i]
But the pointer array was not dynamic allocated, so you must not delete it.

If you used string *dates[3]; then it shouldn't compile, as you are asignning a char* to a string*.
If you use string dates[3]; it will compile, but there will be leaks, as the string performs a copy.
Topic archived. No new replies allowed.