Since you are using C++, you should use features this language provides you instead of struggling with C-style code. It's good that you decided to use std::vector
so continue and use std::string
for storing strings, std::istringstream
for creating an input stream that you will read the tokens from and std::getline
to actually retrieve these tokens.
At first, use an access specifier public
to make the attributes of the elemente
class available outside the scope of this class and change the type of name
to std::string
:
class elemente
{
public:
std::string name;
// ...
};
Then retrieving tokens from the line could look like this:
#include <iostream>
#include <vector>
#include <sstream>
...
std::vector<elemente> elements;
std::string line("this is my input line");
std::istringstream lineStream(line);
for (std::string word; std::getline(lineStream, word, ' '); )
{
if (!word.empty())
{
elements.push_back(elemente());
elements.back().name = word;
}
}
And to test this code, you can just print all names stored within elements of this vector:
std::vector<elemente>::iterator e;
for(e = elements.begin(); e != elements.end(); ++e)
std::cout << e->name << ".";
outputs:
this.is.my.input.line.
Alternatively you could create a public constructor of your class so that you can construct your elements with properly initialized members:
class elemente
{
public:
elemente(const std::string& s) : name(s){ }
// ...
std::string name;
// ...
};
Then parsing of tokens would become:
for (std::string word; std::getline(lineStream, word, ' '); )
{
if (!word.empty())
elements.push_back(elemente(word));
}
Hope this helps :)