如何在c++中解析引号和逗号
How to parse quotation marks and comma in c++
本文关键字:c++ 更新时间:2023-10-16
我有一个巨大的文件要解析。以前,它由space
或comma
分隔,我使用sscanf(string, "%lf %lf ", &aa, &bb);
将数据获取到我的程序中。
但现在数据格式改为"122635.670399999","209705.752799999"
,同时使用逗号和引号。我不知道该怎么处理。
事实上,我以前的代码是在网上找到的,我很难找到解决这类问题的合适文档。如果你能向我推荐一些就太好了。
与其读取字符串,然后从字符串中删除逗号和引号,最后将数据转换为数字,我可能会创建一个区域设置对象,将逗号和引号分类为空白,在流中注入该区域设置,然后读取数字,而不必再重复。
// here's our ctype facet:
class my_ctype : public std::ctype<char> {
public:
mask const *get_table() {
static std::vector<std::ctype<char>::mask>
table(classic_table(), classic_table()+table_size);
// tell it to classify quotes and commas as "space":
table['"'] = (mask)space;
table[','] = (mask)space;
return &table[0];
}
my_ctype(size_t refs=0) : std::ctype<char>(get_table(), false, refs) { }
};
使用它,我们可以读取这样的数据:
int main() {
// Test input from question:
std::string input(""122635.670399999","209705.752799999"");
// Open the "file" of the input (from the string, for test purposes).
std::istringstream infile(input);
// Tell the stream to use the locale we defined above:
infile.imbue(std::locale(std::locale(), new my_ctype));
// Read the numbers into a vector of doubles:
std:vector<double> numbers{std::istream_iterator<double>(infile),
std::istream_iterator<double>()};
// Print out the sum of the numbers to show we read them:
std::cout << std::accumulate(numbers.begin(), numbers.end(), 0.0);
}
请注意,一旦我们使用ctype方面为流注入了区域设置,我们就可以读取数字,就好像逗号和引号根本不存在一样。由于ctype方面将它们归类为空白,除了充当其他东西之间的分隔符之外,它们被完全忽略了。
我指出这一点主要是为了清楚地表明,在那之后的任何处理都没有魔力。如果您喜欢使用istream_iterator
而不是(例如)double value; infile >> value;
,则没有什么特别之处。你可以用通常读取用空格分隔的数字的任何方式读取这些数字——因为就流而言,这正是你所拥有的。
如果字符串中有逗号分隔的数据,那么只需从字符串中删除"
,如下所示:假设字符串是str1
str1.erase(std::remove(str1.begin(), str1.end(), '"'), str1.end());
这将擦除所有出现的"
//Use below code to convert string into float
float f1;
std::stringstream ss;
ss<<str1;
ss>>f1;
相关文章:
- 没有找到相关文章