如何将字符串流与多个分隔符一起使用

How to use istringstream with more than one delimiter

本文关键字:分隔符 一起 字符串      更新时间:2023-10-16

嗨,我想问一下如何从字符串中解析多个浮点数,由"/"和空格分隔。

文件中的文本格式为"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()进行解析,但我对两者都了解不多,并希望得到一些建议。

如果你使用 std::

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 拆分字符串