- 论坛徽章:
- 0
|
我也贴个C++的。- #ifdef _MSC_VER
- #define _SCL_SECURE_NO_WARNINGS 1
- #endif
- #include <string>
- #include <vector>
- #include <iostream>
- #include <fstream>
- #include <boost/foreach.hpp>
- #include <boost/lexical_cast.hpp>
- #include <boost/algorithm/string.hpp>
- // 对应一行的数据
- typedef std::vector<int> ResultLineType;
- // 所有的行
- typedef std::vector<ResultLineType> ResultVectorType;
- // 打印结果
- void print_result(const ResultVectorType &result_vec)
- {
- std::cout << "total line: " << result_vec.size() << std::endl;
- // 一行一行的输出
- for (size_t m = 0; m < result_vec.size(); ++m)
- {
- const ResultLineType &line_vec = result_vec[m];
- // 输出行号,空行也输出行号
- std::cout << "line" << m + 1 << ":\t";
- if (line_vec.empty())
- {
- std::cout << std::endl;
- continue;
- }
- // 遍历一行中的各个数值
- for (size_t n = 0; n < line_vec.size(); ++n)
- {
- std::cout << line_vec[n];
- if (n == line_vec.size() - 1)
- std::cout << std::endl;
- else
- std::cout << " ";
- }
- }
- }
- // ifs 输入
- // result_vec 结果
- int parse_stream(std::ifstream &ifs, ResultVectorType &result_vec)
- {
- // 行数,从1开始
- int line_count = 0;
- // 读到的一行字符串
- std::string line;
- // 字符串去除逗号和空白后的字符串结果集合
- std::vector<std::string> split_vec;
- // 从split_vec转换成的整数结果集合
- ResultLineType result_line;
- // 每次处理一行
- for (;;)
- {
- std::getline(ifs, line);
- if (!ifs.good())
- break;
- ++line_count;
- split_vec.clear();
- result_line.clear();
- // 跳过空行
- if (line.empty())
- {
- result_vec.push_back(result_line);
- continue;
- }
- // 分割字符串
- boost::split(split_vec, line, boost::is_any_of(" ,\r\n"), boost::token_compress_on);
- try
- {
- // 转换成整数
- BOOST_FOREACH (std::string &str, split_vec)
- {
- int num = boost::lexical_cast<int>(str);
- result_line.push_back(num);
- }
- // 存入
- result_vec.push_back(result_line);
- }
- catch (const boost::bad_lexical_cast &)
- {
- // 格式错误则中断处理
- std::cerr << "error: file format error, line: " << line_count << std::endl;
- return 3;
- }
- }
- return 0;
- }
- int main(int argc, char **argv)
- {
- if (argc != 2)
- {
- std::cerr << "usage: fl <filepath>" << std::endl;
- return 1;
- }
- // 只读方式打开文件
- std::ifstream ifs(argv[1], std::ios_base::in);
- if (!ifs.good())
- {
- std::cerr << "error: can not read file." << std::endl;
- return 2;
- }
- ResultVectorType result_vec;
- // 处理
- int ret = parse_stream(ifs, result_vec);
- if (ret == 0)
- {
- // 打印结果
- print_result(result_vec);
- }
- ifs.close();
- return ret;
- }
复制代码 |
|