Oct 5, 2012 at 8:35am UTC
Hello,
Converting from String to Char is easy with...
#include <iostream>
#include <string>
void main()
{
unsigned int i;
string StrName = "TheFile.txt";
char FileName[20];
for (i=0;i<=StrName.size();i++)
{
FileName[i]=StrName[i];
}
}
But I cannot put it in a subroutine without an error.
#include <iostream>
#include <string>
void main()
{
string StrName = "TheFile.txt";
char GetTheName(string tit);
char n[20] = GetTheName(StrName);
}
char GetTheName(string tit)
{
unsigned int i;
char FileName[20];
for (i=0;i<=tit.size();i++)
{
FileName[i]=tit[i];
}
return FileName[20];
}
Somebody, please?
Oct 5, 2012 at 9:04am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <string>
int main()
{
string StrName = "TheFile.txt" ;
char * GetTheName( char *s, const string &tit, size_t n );
char n[20];
GetTheName(n, StrName, 20 );
return 0;
}
char * GetTheName( char *s, const string &tit, size_t n )
{
std::strncpy( s, tit.c_str(), n );
s[n-1] = '\0' ;
return ( s );
}
Last edited on Oct 5, 2012 at 9:04am UTC
Oct 8, 2012 at 11:54pm UTC
Great!!
Thank you very much!!
-elmimo
Oct 10, 2012 at 4:20am UTC
Btw,
do you know why
s[n-1] is okay, but if we change this:
#define AllName "TheFile.txt"
...
string StrName = AllName;
then s[n] is okay??
Oct 10, 2012 at 10:16am UTC
s[n] is not okay because the memory outside the array will be overwritten.
Oct 11, 2012 at 8:30am UTC
Hi again,
Actually, I tried and it is okay.
I was thinking about an explanation on whether the index of the array starts with 1 when changing from #define to string, and with 0 in the other case... but not sure now.
In any way, thanks.
-elmimo
Last edited on Oct 11, 2012 at 8:31am UTC