1

I have a string that I want to show on the winbgi window using outtextxy.

The problem is outtextxy only takes the pointer of a char array which shows a compiler error.

Here is the code

for(int i=0;i<13;i++){
        setcolor(RED);
        circle(otab[i].x1,otab[i].y1,otab[i].radius);
        string txt="obs";
        txt.append(1,i);
        outtextxy(otab[i].x1,otab[i].y1,txt);
}

Clifford
  • 88,407
  • 13
  • 85
  • 165
AidenFive
  • 29
  • 1
  • 7
  • Compiler diagnostics are emitted to assist diagnosis. Although the issue here is perhaps clear to anyone familiar with the signature of `outtextxy()`, the diagnostic would make the issue clear to anyone without such familiarity. For that reason it is reasonable and useful to include the diagnostic (compiler error) verbatim (copy & paste in its entirety) into your question. "_shows a compiler error_" is not really helpful to your cause. – Clifford Apr 06 '22 at 22:15

2 Answers2

1

if string is a std::string, use txt.c_str()

https://www.cplusplus.com/reference/string/string/c_str/

Clifford
  • 88,407
  • 13
  • 85
  • 165
on8tom
  • 1,766
  • 11
  • 24
  • it gives me the error "cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '3' to 'void outtextxy(int, int, char*)' " – AidenFive Jun 04 '20 at 12:10
  • probably because outtextxy requires a char* instead of a const char *, If outtextxy doesn't modify the text, pleas bug the developer of that functon to take a const char * as an input, otherwise you need to duplicate the the string to a char *. – on8tom Jun 04 '20 at 12:13
  • 1
    @AidenFive -- `outtextxy` comes from the olden days when C programmers weren't very concerned about `const` correctness. In this case, it's okay to cast the return value to a `char*`: `outtextxy(x, y, (char*)txt.c_str())`. Don't make casts like this a habit. – Pete Becker Jun 04 '20 at 12:28
  • @PeteBecker : better yet: `const_cast(txt.c_str())`. – Clifford Apr 06 '22 at 22:10
0

thanks everyone for the answers. here is the updated code.

    for(int i=0;i<13;i++){
        setcolor(RED);
        circle(otab[i].x1,otab[i].y1,otab[i].radius);
        string txt="obs:";
        std::ostringstream oss;//i used ostringstream because append didn't work properly
        oss << txt << i;
        string pl=oss.str(); 
        outtextxy(otab[i].x1,otab[i].y1,(char*)pl.c_str());
    }

AidenFive
  • 29
  • 1
  • 7
  • I would suggest `const_cast(oss.str().c_str())` to document the kludge to work around poor API const-correctness, and to avoid the unnecessary intermediate `pl`. Moreover whilst answering your own question is fine, if @on8tom's answer led you to this solution, then you should mark his answer as accepted. It is not normal to post an answer simply as an update - SO is not a discussion forum. – Clifford Apr 06 '22 at 22:03