getline读取同时包含空格和逗号分隔的字符串 [英] getline to read in a string that has both white spaces and is comma seperated

查看:249
本文介绍了getline读取同时包含空格和逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个文件,该文件的字符串如下:

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

12/10/11下午12:30,67.9,78,98

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

...

...

我想这样分开

12/11/10 下午12:30 67.9

10/11/12 12:30 PM 67.9

我知道您使用getline来分隔逗号分隔的内容:

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, ' ')

将空格读入my_string

would read in the spaces into my_string

那么还有其他方法可以解决这个问题吗? 另外,我需要怎么做才能跳过最后2个(78,98)并转到下一行? getline(infile, 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?

推荐答案

为您的流提供一个面,该面将逗号解释为空格(这将是我们的分隔符).然后只需创建一个重载operator>>()函数并利用此新功能的类即可. istream::ignore是要跳过字符时使用的功能.

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演示

这篇关于getline读取同时包含空格和逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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