getline to read in a string that has both white spaces and is comma seperated

心已入冬 提交于 2020-06-29 06:32:05

问题


Okay, so i have a file that has a string like so:

10/11/12 12:30 PM,67.9,78,98

...

...

I want to separate it like so

10/11/12 12:30 PM 67.9

I know you use getline to separate the comma separated stuff:

getline(infile, my_string, ',')

but I also know that doing this to get the date:

getline(infile, my_string, ' ')

would read in the spaces into my_string

so is there any other way to go about this? Also, what would I need to do to skip over the last 2 (78,98) and go to the next line? Would just a getline(infile, my_string) suffice?


回答1:


You can read the string with getline and then use sscanf to read the formatted string :)




回答2:


Consider using boost libraries that supplement the STL http://www.boost.org/doc/libs/1_57_0/doc/html/string_algo/usage.html




回答3:


Give your stream a facet that interprets commas as whitespace (which will be our delimiter). Then just make a class that overloads the operator>>() function and leverages this new functionality. istream::ignore is the function use when you want to skip characters.

#include <iostream>
#include <vector>
#include <limits>

struct whitespace : std::ctype<char> {
    static const mask* get_table() {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v[','] |=  space;  // comma will be classified as whitespace
        v[' '] &= ~space;      // space will not be classified as whitespace
        return &v[0];
    }

    whitespace(std::size_t refs = 0) : std::ctype<char>(get_table(), false, refs) { }
};

template<class T>
using has_whitespace_locale = T;

struct row {
    friend std::istream& operator>>(has_whitespace_locale<std::istream>& is, row& r) {
        std::string temp;
        is >> r.m_row >> temp;
        r.m_row += temp;
        is.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip the rest of the line
        return is;
    }

    std::string get_row() const { return m_row; }
private:
    std::string m_row;
};

// Test

#include <sstream>
#include <string>
int main() {
    std::stringstream ss("10/11/12 12:30 PM,67.9,78,98\n4/24/11 4:52 AM,42.9,59,48");
    std::cin.imbue(std::locale(std::cin.getloc(), new whitespace));
    row r;
    while (ss >> r) {
        std::cout << r.get_row() << '\n';
    }
}

Coliru Demo



来源:https://stackoverflow.com/questions/35806891/getline-to-read-in-a-string-that-has-both-white-spaces-and-is-comma-seperated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!