2012-09-19 25 views
2

您好我想问一下如何从字符串中解析多个由“/”和空格分隔的浮点数。如何使用具有多个分隔符的istringstream

该文件的文本格式是“f 1/1/1 2/2/2 3/3/3 4/4/4” 我需要将这行文本中的每个整数解析为几个int变量,然后用它来构造一个“脸”对象(见下文)。

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()实现,但我已经通过我的UNI讲师警告从了,所以我要寻找一个替代。我也不允许其他第三方库,包括boost。

正则表达式和用stringstream()解析已被提及,但我真的不知道太多,并会感谢一些建议。

+0

你想分析12个整数,在四组三个,分成九个变量,五个单独的和四个数组?这怎么能让人觉得呢? –

+0

尽管问题最初看起来不像重复,但您似乎想要做的事情已在之前的答案中进行了介绍:http://stackoverflow.com/a/2909187/179910 –

回答

1

如果你正在阅读性病文件:: 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); 
} 
0

你可以使用boost :: split。

样品的例子是:

string line("test\ttest2\ttest3"); 
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

而且相关:

Splitting the string using boost::algorithm::split

+0

我的歉意。它让我意识到我被告知要避免任何非标准的图书馆(因为我的讲师不会拥有这些图书馆)。 –

1

考虑到你的榜样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是(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]); 
1

我会做到这一点的方法是change the interpretation of space包括其他分隔符。如果我想要,我会使用不同的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 

即第一个值后面输入一个空格和第二个值后斜杠。