Error writing text file: cannot Convert Std::string to const char*

Asked

Viewed 836 times

2

I’m not getting a record string on file .txt in C++ (Codeblocks).

// aux é um inteiro
// aux2 é uma string
// foi dado fopen no arquivo...abaixo só segue a parte com erro   

aux = x.retorne_energia();
aux2 = x.retorna_nome();
fprintf(arquivo,"%d",aux);

fputs(aux2,arquivo);
aux1 = y.retorne_energia();
aux2 = y.retorna_nome();

fprintf(arquivo,"%d %s",aux,aux2);
fclose(arquivo);

How can I fix the errors below?

error: cannot Convert 'Std::string {aka Std::basic_string}' to 'const char*' for argument '1' to 'int fputs(const char*, FILE*)'|

error: cannot pass Objects of non-trivially-copyable type 'Std::string {aka class Std::basic_string}' through '...'|

format '%s' expects argument of type 'char*', but argument 4 has type 'Std::string {aka Std::basic_string}' [-Wformat]|

1 answer

1


The functions fprintf and fputs accept the type const char *, you are passing a variable std::string.

Use c_str() to use the variable as C-string:

// ...
fputs(aux2.c_str(), arquivo);
// ...
fprintf(arquivo,"%d %s", aux, aux2.c_str());
  • Thank you sunstreaker, it worked the way you spoke.

  • @Iagoochoa You have to make the same transformation in the case of fprintf also.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.