如何将字符串流与多个分隔符一起使用
How to use istringstream with more than one delimiter
嗨,我想问一下如何从字符串中解析多个浮点数,由"/"和空格分隔。
文件中的文本格式为"f 1/1/1 2/2/2 3/3/3 4/4/4"我需要将这行文本中的每个整数解析为几个 int 变量,然后用于构造一个"face"对象(见下文)。
int a(0),b(0),c(0),d(0),e(0);
int t[4]={0,0,0,0};
//parsing code goes here
faces.push_back(new face(b,a,c,d,e,t[0],t[1],t[2],t[3],currentMaterial));
我可以用 sscanf() 来做到这一点,但我的大学讲师警告我不要这样做,所以我正在寻找替代方案。 我也不允许使用其他第三方库,包括 boost。
已经提到了正则表达式和使用stringstream()进行解析,但我对两者都了解不多,并希望得到一些建议。
ifstream 读取文件,首先就不需要 std::istringstream(尽管使用两者非常相似,因为它们继承自同一个基类)。以下是使用 std::ifstream 的方法:
ifstream ifs("Your file.txt");
vector<int> numbers;
while (ifs)
{
while (ifs.peek() == ' ' || ifs.peek() == '/')
ifs.get();
int number;
if (ifs >> number)
numbers.push_back(number);
}
考虑到您的示例f 1/1/1 2/2/2 3/3/3 4/4/4
您需要阅读的是:char int char int char int int char int char int int char int char int
为此:
istringstream is(str);
char f, c;
int d[12];
bool success = (is >> f) && (f == 'f')
&& (is >> d[0]) && (is >> c) && (c == '/')
&& (is >> d[1]) && (is >> c) && (c == '/') &&
..... && (is >> d[11]);
我这样做的方法是更改空间的解释以包含其他分隔符。如果我想花哨,我会使用不同的std::ostream
对象,每个对象都有一个std::ctype<char>
面来处理一个分隔符,并使用共享std::streambuf
。
如果要明确使用分隔符,则可以改用合适的机械手跳过分隔符,或者,如果不存在,则指示故障:
template <char Sep>
std::istream& sep(std::istream& in) {
if ((in >> std::ws).peek() != std::to_int_type(Sep)) {
in.setstate(std::ios_base::failbit);
}
else {
in.ignore();
}
return in;
}
std::istream& (* const slash)(std::istream&) = Sep<'/'>;
代码未经测试并在移动设备上键入,即可能包含小错误。您将读取如下数据:
if (in >> v1 >> v2 >> slash >> v3 /*...*/) {
deal_with_input(v1, v2, v3);
}
注意:上述使用假定输入为
1.0 2.0/3.0
即第一个值之后的空格和第二个值之后的斜杠。
你可以使用 boost::split。
示例为:
string line("testttest2ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
更多信息在这里:
http://www.boost.org/doc/libs/1_51_0/doc/html/string_algo.html
并且还相关:
使用 boost::algorithm::split 拆分字符串
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将C++中的库和头与MinGW一起使用
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我不能将 rand() 与数组的大小一起使用?
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 当用户键入分隔符时,停止getline()输入
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 将fold表达式与std::一起用于两个元组
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 将 std::allocate_shared 与多态资源分配器一起使用
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 将 exprtk 与自定义类的对象一起使用
- 如何将字符串流与多个分隔符一起使用
- 如何识别分隔符以及如何将其与路径一起使用 打开 Inventor
- 用户定义字面值如何与数字分隔符一起使用