How, in a subroutine, convert String to Char?

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?
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
Great!!

Thank you very much!!

-elmimo
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??
s[n] is not okay because the memory outside the array will be overwritten.
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
Actually, I tried and it is okay.


Crossing the street without looking for oncoming traffic is "okay" occasionally, too.
Topic archived. No new replies allowed.