我有一个巨大的文件要解析。以前,它由space
or分隔comma
,我曾经sscanf(string, "%lf %lf ", &aa, &bb);
将数据放入我的程序中。
但现在数据格式改为"122635.670399999","209705.752799999"
,同时带有逗号和引号。我不知道如何处理它。实际上,我之前的代码是在网上找到的,我很难为这类问题找到合适的文档。如果你能推荐一些给我,那就太好了。谢谢。
我有一个巨大的文件要解析。以前,它由space
or分隔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 facet 为流注入了语言环境,我们就可以读取数字,就好像逗号和引号根本不存在一样。由于 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;