我正在尝试使用分隔符从文件中拆分数据,但之后我想再次使用空格拆分某些字符串,但我一直遇到编译器错误。部分代码如下...
PS:我没有分享所有代码,所以如果它看起来不完整,这就是为什么,我只是在寻找一种重新拆分所选字符串的方法。
bool loadProperties(char* residential, char* commercial,
PropertyContainer* thePropertyContainer) {
ifstream propertyFile;
int datapos = 6;
Property* propertyType = NULL;
propertyFile.open(residential, ios::in);
if (!propertyFile.is_open()) {
cout << "Cant open file: " << residential << endl;
return false;
}
while (propertyFile.good()) {
getline(propertyFile, buffer);
typedef tokenizer<char_separator<char> > tokenizer;
char_separator<char> sep("\n\t\0,*");
tokenizer tokens(buffer, sep);
for (tokenizer::iterator pos = tokens.begin();
pos != tokens.end(); ++pos) {
if (!validate(datapos, *pos)) {
return false;
}
switch(datapos) {
case 6:
vector < string > splitstring; <------------------------ (LINE 127)
boost::split(splitstring, *pos, boost::is_any_of(" ")); <------this is where I am trying to split via white space for a second time.
if (splitstring[0] == "RS") {
propertyType = new ResSales;
} else if (splitstring[0] == "RS") {
propertyType = new ResRentals;
} else {
return false;
}
break;
case 7:
propertyType->setOwner(*pos);
break;
case 8:
propertyType->setAddress(*pos);
break;
case 9:
propertyType->setSuburb(*pos);
break;
case 10:
propertyType->setPostcode(changeString<int>(*pos));
break;
case 11:
dynamic_cast<Residential*>(propertyType)->setBedrooms
(changeString<int>(*pos));
break;
case 12:
if (propertyType->getType() == "ResSales") {
dynamic_cast<Sales*>(propertyType)->setAuctionDate(*pos);
} else if (propertyType->getType() == "ResRentals") {
dynamic_cast<Rentals*>(propertyType)->setBond
(changeString<double>(*pos));
}
break;
case 13:
if (propertyType->getType() == "ResSales") {
dynamic_cast<Sales*>(propertyType)->setPrice
(changeString<double>(*pos));
} else if (propertyType->getType() == "ResRentals") {
dynamic_cast<Rentals*>(propertyType)->setMonthlyRent
(changeString<double>(*pos));
}
break;
}
if (datapos >= 14) {
thePropertyContainer->addProperty(propertyType);
datapos = 6;
} else {
++datapos;
}
}
}
propertyFile.close();
return true;
}
基本上,如果 case 是 6,我想再次用空格拆分 token ,我不知道如何实现这个,我正在尝试使用 boost,如你所知。但我得到了错误....
非常感谢任何帮助,谢谢。
更新:在与一些人讨论后续问题的评论后,问题似乎与 switch 语句范围有关,只需要阻止代码部分并像对待现在一样工作,谢谢大家。
最佳答案
您似乎在关注与 Boost documentation 中的示例类似的示例, 但缺少一行。
typedef vector < string > splitstring;
splitstring stringthathasbeensplit;
boost::split(stringthathasbeensplit, *pos, boost::is_any_of(" "));
问题是,您要声明 splitstring
是类型 vector<string>
的别名. split
将采用 vector<string>
的对象类型,但不是 定义 本身 - 这就是您通过传递 splitstring
传递的内容.
真的,你应该放弃 typedef
所有一起直接声明一个类型的对象 vector<string>
,因为 typedef 在这种情况下没有任何作用。如果删除 typedef
关键字,它将按照您编写的方式工作。
vector < string > splitstring;
boost::split(splitstring, *pos, boost::is_any_of(" "));
关于c++ - 在 C++ 中使用 boost 拆分字符串两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30273121/