MickeyKSP
MickeyKSP

Reputation: 43

Converting vector<char> to const char* and string

How to convert vector to const char* ? Also to string? Is this even legal?

void Printer::Wrap(const CharVector& text, RangeVector& result) const
    //if (TestLineWidth(text.begin(), text.end()))
    int c = 0;
    for (CharVector::const_iterator it = text.begin(); it != text.end(); ++it)
        c++;
    if (TestLineWidth(&text[0], &text[c]))

Here are declarations of CharVector and TestLineWidth:

typedef std::vector<char> CharVector;

bool TestLineWidth(const char* from, const char* to) const;

Upvotes: 1

Views: 7075

Answers (2)

alexandre decuq
alexandre decuq

Reputation: 24

And if you want to convert the string into a char* you can use yourString.c_str() cf C++ documentation: http://www.cplusplus.com/reference/string/string/c_str/

Upvotes: -1

Patryk Wertka
Patryk Wertka

Reputation: 169

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<char> data = {'h', 'e', 'l', 'l', 'o', '!'};
    cout << string(begin(data), end(data)) << endl;
    return 0;
}

For const char *, you cant just call data.data(), becouse C-string are null terminated, so you'll have to append '\0' at the end

Upvotes: 2

Related Questions