获取线,以读取具有空格和逗号分隔的字符串
getline to read in a string that has both white spaces and is comma seperated
好的,所以我有一个文件,其中包含如下字符串:
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';
}
}
科里鲁演示
相关文章:
- 如何分隔字符串并将标记传递给方法
- C++ 用空格和逗号分隔字符串
- 如何将整数值解析为逗号分隔字符串中的单独 int 变量?
- 如何分隔字符串并将每个部分存储在不同的向量中
- 如何按特定分隔符分隔字符串
- 逗号分隔字符串的总和,例如 O(n) 中的 4,1,3
- 如何使用符号分隔字符串而不是空格的输入字符串流
- C++中将不同类型的变量列表连接到逗号分隔字符串的最快方法是什么?
- C++ sscanf 空格分隔字符串
- 在C++中分隔字符串并存储到数组中的最佳方法
- 使用 find_first_of() 和 substr() 分隔字符串,但我得到的输出不正确
- 正在分析逗号分隔字符串中的整数
- 分析分隔字符串
- 用空格分隔字符串的最简单方法
- 分隔字符串的最佳ASCII字符是什么
- C++用空格和标点符号分隔字符串
- c#中分隔字符串中的数字和单位
- 如何基于标记分隔字符串
- c++使用wstring拆分unicode分隔字符串
- 如何在C++中用逗号分隔字符串