我在将strcpy
与自己类的实例的vector
一起使用时遇到了一些问题。这是课程:
class elemente {
char name[5];
short val;
bool red;
};
所以,我从这个类中制作了一个向量:
vector<elemente> ele(1);
但如果我尝试进行此操作:
strcpy(ele.back().name, strtok(line, " "));
我总是有"分段错误"。为什么?
我使用GDB调试我的程序,line
变量是正确的,而且如果我用普通的char *
替换向量,一切都很好(程序不起作用,但内容很好)。
我能做什么?
由于您使用的是C++,因此应该使用该语言提供的功能,而不是使用C风格的代码。很好,您决定使用std::vector
,所以继续使用std::string
来存储字符串,使用std::istringstream
来创建一个输入流,从中读取令牌,并使用std::getline
来实际检索这些令牌。
首先,使用访问说明符public
使elemente
类的属性在此类的范围之外可用,并将name
的类型更改为std::string
:
class elemente
{
public:
std::string name;
// ...
};
然后从行中检索令牌可能如下所示:
#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;
}
}
为了测试这个代码,您只需打印存储在这个向量的元素中的所有名称:
std::vector<elemente>::iterator e;
for(e = elements.begin(); e != elements.end(); ++e)
std::cout << e->name << ".";
输出:
this.is.my.input.line.
或者,你可以创建一个类的公共构造函数,这样你就可以用正确初始化的成员来构造元素:
class elemente
{
public:
elemente(const std::string& s) : name(s){ }
// ...
std::string name;
// ...
};
然后,令牌的解析将变成:
for (std::string word; std::getline(lineStream, word, ' '); )
{
if (!word.empty())
elements.push_back(elemente(word));
}
希望这有帮助:)