Mohamed Tarek
Mohamed Tarek

Reputation: 131

C++ - How to convert char* to std::list<char>

This is a beginner type of question

I'm just wondering if there is a way to convert a null terminated char* to std::list.

Thank you

char* data = ...
std::list<char> clist = convert_chars2list(data);
...
convert_chars2list(char* somedata)
{
    //convert
}

Upvotes: 1

Views: 3521

Answers (6)

Pavan Chandaka
Pavan Chandaka

Reputation: 12761

Let C++ standard library take care of pointer handling and iterator traversing.

std::string str = "Hello world";

Though you can access each character with [] operator from std::string itself, if you want a list of characters

std::list<char> chars(str.begin(), str.end());

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126442

This is probably the simplest way:

#include <list>
#include <string>

int main() 
{ 
    char const* data = "Hello world";
    std::list<char> l(data, data + strlen(data));
}

It exploits the fact that std::string has an interface which is compatible with STL containers.

Upvotes: 9

Caesar
Caesar

Reputation: 9843

If your char* is a C-style string than you can do this (that means it ends with a \0)

#include <list>

int main()
{
    char hello[] = "Hello World!";

    std::list<char> helloList;

    for(int index = 0; hello[index] != 0; ++index)
    {
        helloList.push_back( hello[index] );
    }    
}

Upvotes: 0

eci
eci

Reputation: 2422

std::list<char> convert_chars2list(char* somedata)
{
  std::list<char> res;
  while (*somedata)
     res.push_back(*somedata++);
  return res;
}

Upvotes: 1

SeedmanJ
SeedmanJ

Reputation: 444

It's really weird to use a std::list to contain characters, if you really want to use stl to contain characters, you could use std::string, which would allow you to do:

char*           data = ....;
std::string     string(data);

Upvotes: -1

Nik Bougalis
Nik Bougalis

Reputation: 10613

std::list<char> convert_chars2list(char *somedata)
{
    std::list<char> l;

    while(*somedata != 0)
        l.push_back(*somedata++);

    // If you want to add a terminating NULL character
    // in your list, uncomment the following statement:
    // l.push_back(0);

    return l;
}

Upvotes: 2

Related Questions