PDA

View Full Version : std::string not defined?



tom66
September 5th, 2009, 04:30 PM
Following code throws errors:



#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int __PyPrintFormat(FILE *stream, std::string fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char *buffer;

if(vasprintf(&buffer, fmt, ap) != -1)
{
fputs(buffer, stream);
free(buffer);
return 0;
}

return 1;
}

int main()
{
__PyPrintFormat(stdout, "int output: %d\n", 5928);
return 0;
}


(yes I know I'm mixing C & C++, but it usually comes out for the better.)

I get errors compiling this:



simpletest.cpp:14: error: ‘std::string’ has not been declared
simpletest.cpp: In function ‘int __PyPrintFormat(FILE*, int, ...)’:
simpletest.cpp:20: error: invalid conversion from ‘int’ to ‘const char*’
simpletest.cpp:20: error: initializing argument 2 of ‘int vasprintf(char**, const char*, char*)’
simpletest.cpp: In function ‘int main()’:
simpletest.cpp:177: error: invalid conversion from ‘const char*’ to ‘int’
simpletest.cpp:177: error: initializing argument 2 of ‘int __PyPrintFormat(FILE*, int, ...)’


I have declared std::string by #including string.h... right?

I'm compiling with g++ simpletest.cpp.

All help appreciated!

MadCow108
September 5th, 2009, 04:33 PM
no its defined in <string>
c++ standard headers have no extension
and the c headers have a added c in front:


#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>

if you have this from a book/tutorial, use a different one because yours is outdated

socool274
September 5th, 2009, 04:34 PM
With strings, strings are not compatible as a parameter of char *. Instead of passing the string, use myString.data(). The data() function returns a char *. This is the first of what I can see. Also, it should be included as <string>. What he ^ said.

MadCow108
September 5th, 2009, 04:37 PM
data() does not return a null terminated string
mostly c_str() is the better choice

tom66
September 5th, 2009, 04:47 PM
Thanks, solved problem :).