string as a function return type

C

C@limero

If I want to declare a function in a header file that returns a
string, I always get an error (something complaining about
a syntax error before an ')').

I have declared:



#ifndef MYHEADER_H
#define MYHEADER_H

string function(int day, int month, int year);

#endif



But then I get always an error from the compiler.

If I change this to

#ifndef MYHEADER_H
#define MYHEADER_H

const char* function(int day, int month, int year);

#endif

I get no error.

But the problem then is, since I use an std::eek:stringstream oss in
the definition, I have to write "ugly" things like

return oss.str().c_str();

Is there a way to bypass this ?
 
V

Victor Bazarov

C@limero said:
If I want to declare a function in a header file that returns a
string, I always get an error (something complaining about
a syntax error before an ')').

I have declared:



#ifndef MYHEADER_H
#define MYHEADER_H

string function(int day, int month, int year);

'string' is a typedef declared in <string> header. You need to include
that header before using 'string'. And use 'std::string' because the
name 'string' (the typedef) is declared in the 'std' namespace. So, the
line above should be replaced with two:

#endif



But then I get always an error from the compiler.

If I change this to

#ifndef MYHEADER_H
#define MYHEADER_H

const char* function(int day, int month, int year);

#endif

I get no error.

But the problem then is, since I use an std::eek:stringstream oss in
the definition, I have to write "ugly" things like

return oss.str().c_str();

Is there a way to bypass this ?

No, there is no way to bypass it. It has to be resolved.

V
 
M

Mike Smith

C@limero said:
If I want to declare a function in a header file that returns a
string, I always get an error (something complaining about
a syntax error before an ')').

I have declared:



#ifndef MYHEADER_H
#define MYHEADER_H

#endif

string is not a built-in type; it is a class, declared in header
<string>, and in namespace std.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top