Parsing a .csv file consisting numbers with charac

2019-09-22 01:46发布

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

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

标签: c++ csv parsing
2条回答
做自己的国王
2楼-- · 2019-09-22 02:14

You are not asking for CSV parsing — you ignore field boundaries — you just want to extract all numbers from a string.

Do that by replacing everything that is not a number with spaces, then using a stringstream to extract.

#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>

int main()
{
  std::string s = "=sjkc(11,32as%2dc 32,43)a-b,49,26),b.'47,28n,a=64";

  std::transform( s.begin(), s.end(), s.begin(), []( char c ) 
  { 
    return std::isdigit( c ) ? c : ' ';
  } );

  std::istringstream ss( s );
  int n;
  while (ss >> n)
    std::cout << n << "\n";
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-09-22 02:27

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

It led to this:

#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;
}

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

查看更多
登录 后发表回答