获取线,以读取具有空格和逗号分隔的字符串

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

本文关键字:分隔 字符串 空格 读取 获取      更新时间:2023-10-16

好的,所以我有一个文件,其中包含如下字符串:

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

我想这样分开

12-11-10下午12:3067,9

我知道你用getline来分隔逗号分隔的东西:

getline(infile, my_string, ',')

但我也知道这样做是为了获取日期:

getline(infile, my_string, ' ')

会把空格读成my_string

那么还有其他方法可以解决这个问题吗?另外,我需要做什么才能跳过最后 2 (78,98) 并转到下一行?只要getline(infile, my_string)就足够了吗?

您可以使用

getline 读取字符串,然后使用 sscanf 读取格式化字符串:)

考虑使用提升库来补充 STL http://www.boost.org/doc/libs/1_57_0/doc/html/string_algo/usage.html

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

#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,98n4/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';
    }
}

科里鲁演示