解析包含数字和字符之间的.csv文件(C ++) [英] Parsing a .csv file consisting numbers with characters in between (C++)

查看:109
本文介绍了解析包含数字和字符之间的.csv文件(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件

I have a file that looks like this

=sjkc(11,32as%2dc 32,43)a-b,49,26),b.'47,28n,a=64  and so on...

目标是检索所有数字,而忽略其间的任何其他字符.没有换行符,因此坐标在整个文件中只是连续的.

The objective is to retrieve all the Digits while ignoring any other characters in between. There is no newline so the coordinates are just continuous throughout the file.

注意:不允许使用正则表达式和地图

Note: Not allowed to use regex and map

因此对于此实例,它应返回数字11,然后是32,然后是2,然后是32,依此类推...

So for this instance, it should return the number 11 then 32 then 2 then 32 and so on...

推荐答案

在此答案中,请杰里·科芬(Jerry Coffin)提供漂亮的例子:

Credit to Jerry Coffin for his nifty example in this answer: How do I iterate over cin line by line in C++?

它导致了这一点:

#include <cctype>
#include <iostream>
#include <locale>
#include <sstream>
#include <vector>

struct digit_reader : std::ctype<char>
{
    digit_reader() : std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask>
            rc(table_size, std::ctype_base::mask());

        for (size_t i = 0; i < table_size; ++i)
        {
            rc[i] = std::isdigit(i) ? std::ctype_base::digit : std::ctype_base::space;
        }
        return &rc[0];
    }
};

int main()
{
    std::stringstream ss("=sjkc(11,32as%2dc 32,43)a-b,49,26),b.'47,28n,a=64");
    ss.imbue(std::locale(std::locale(), new digit_reader()));

    int num;
    while (ss >> num)
    {
        std::cout << num << ' ';
    }
    std::cout << "\n";
    return 0;
}

您应该能够使用此方面使任何输入流(例如std :: cin或std :: ifstream)注入,并跳过除数字以外的所有内容.

You should be able to imbue any input stream, like std::cin or a std::ifstream, with this facet and skip everything but numbers.

这篇关于解析包含数字和字符之间的.csv文件(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆