wasmith92
wasmith92

Reputation: 11

Calling an element of a string as a char in C++

This is for use in a GUI using C++ and FLTK.

Say I have a string x = "ABCDEFG" and an array of boxes y[7].

I'd want to put one of those letters as the label on a box using a for loop such as:

for (int i=0; i<7; i++) {   
  y[i] = new Fl_Box(120+31*i,40,30,30,"A");
}

but rather than "A" on all of them, of course I'd want "A" on y[0], "B" on y[1], "C" on y[2], etc - with the letter called from the string as the element x[i].

I tried simply using x[0], etc and found that it needed a conversion to char.

I then tried &x[0] and found it just prints the whole string on each of them as its a const char.

Upvotes: 0

Views: 123

Answers (2)

Mark Hendrickson
Mark Hendrickson

Reputation: 689

you can use the substr() method of std::string like:

for (int i=0; i<7; i++) {   
  y[i] = new Fl_Box(120+31*i,40,30,30, x.substr(i, 1).c_str());
}

Here is the signature of substr():

string substr (size_t pos = 0, size_t len = npos) const;

Here is a quick test program an its output.

#include <stdio.h>
#include <string>
int main(int argc, char *argv[])
{
    std::string x = "ABCDEFG";
    for (int i = 0; i < 7; ++i) {
        printf("i(%d) c(%s)\n", i, x.substr(i, 1).c_str());
    }
    return 0;
}

# ./a.out
i(0) c(A)
i(1) c(B)
i(2) c(C)
i(3) c(D)
i(4) c(E)
i(5) c(F)
i(6) c(G)

Upvotes: 1

ppl
ppl

Reputation: 1120

Assuming FL_Box expects a C-string style (null terminated), consider using a temporary value.

std::string(x[i], 1).c_str()

This is similar to passing

char temp[2] = { 0 };
temp[0] = x[i];

and passing temp.

Upvotes: 1

Related Questions