开发者

convert a line to a Node in C++

I'm trying to write a function that takes a line as a string and converts it into a Node.

Node convertLineToNode(string line){
    char lineC开发者_Go百科[] = line;
    Node *n = new Node();
    n->lastname=strtok(lineC," ");
    n->name=strtok(lineC," ");
    n->ID=strtok(lineC," ");
 }

However it doesn't work properly. It expects the string line as char array. I couldn't convert it into char array. Is there any solutions for my problem?


The C++ way would be this:

Node* convertLineToNode(std::string const & line)
{
   std::istringstream iss(line);
   Node *n = new Node();
   iss >> n->lastname
       >> n->name
       >> n->ID;
   return n;
}

consider returning a shared_pointer instead of a raw one


string::c_str() will return the C String representation.

However, instead of using c string libraries (strtok), I would consider rewriting your method to make use of the std::string methods, or even the boost regex library.


thats probably because your n->lastname has a string data type. The strtok returns char* so make sure your data structures corresponds well with what the function returns.


It could also work like this, if Nodes can be copied:

Node convert(string line) {
   Node n;
   n.lastname = "abc";
   return n;
 }

But Node will need to support copying:

Node n = convert("abc");

The copying can be implemented by copy constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜