C++如何读取文件并解析逗号分隔值
C++ how to read a file and parse the comma separated value
如何读取文件,并获取逗号分隔值的最后一部分,用于求和。 例如:我有这个文件名和这个数据
2014-12-22.16:31:36,3,3
2014-12-22.16:31:37,3,6
2014-12-22.16:31:38,3,9
2014-12-22.16:31:39,6,15
我想要得到的实际上是数字 15 作为整数。 所以我可以用其他数字做加法。 但任何其他方式也可以.. 数字 15 本质上是逗号分隔值的所有第 2 部分的总和。我有阅读部分
if(IsFileExist(theFileName)) {
std::ifstream file(theFileName);
std::string str;
while (std::getline(file, str)) {
}
}
获得该行后,搜索最后一个逗号,该逗号后应跟要求和的数据。使用 std::stoi()
转换子字符串:
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <string> // std::string, std::getline
int main()
{
int sum(0);
for (std::string line; std::getline(file, line); )
{
std::string::size_type pos = line.find_last_of(',');
try
{
sum += std::stoi(line.substr(pos+1));
}
catch (...)
{
std::cerr << "Invalid CSVn";
csv.setstate(std::ios_base::failbit);
}
}
std::cout << sum;
}
根据我的经验,如果您的 CSV 包含特别,
符号,您必须使用一些真正的库。您可以考虑使用Boost Tokenizer(http://www.boost.org/doc/libs/1_55_0/libs/tokenizer/(。但是,如果您的数据从未包含,
则仅使用字符串吐槽方法
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << 'n';
}
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 读取制表符分隔的文件时出现问题 C++
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 如何将逗号分隔的文件读取为 2D int 数组?
- 读取带有分隔C++的文件
- 嵌套结构,从由空行分隔的文件中读取数据
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取用空格分隔的数字
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- C++将分隔文件导入矢量
- C++ 在关键字段上联接两个管道分隔文件
- 当数据包含空格时,如何将制表符分隔文件的内容加载到C++字符串的 2D 向量中
- C++ 读取分隔文件并创建对象
- C++:读取分隔文件并存储在结构中
- 如何读取分隔文件的最后一行
- 如何在 Xcode 中分隔文件类
- visual c++6-用c++编辑管道分隔文件