尝试用sstream替换scanf

Trying to replace scanf with sstream

本文关键字:替换 scanf sstream      更新时间:2023-10-16

我正在尝试解析一个文件。我目前正在使用以下代码,但希望将其替换为基于sstream的解决方案

unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
const char* cstring = line.c_str();
int matches = sscanf(cstring, "f %d/%d/%d %d/%d/%d %d/%d/%dn", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);

当我尝试以下操作时,我得到了意想不到的结果

std::stringstream f(line);
f >> vertexIndex[0] >> uvIndex[0] >> normalIndex[0] >> vertexIndex[1] >> uvIndex[1] >> normalIndex[1] >> vertexIndex[2] >> uvIndex[2] >> normalIndex[2];

我肯定我误解了流的使用…任何帮助都太棒了!

这纯粹是缺乏理解。这个问题的解决方案是:

std::stringstream ss(line.substr(2)); 
char throwaway; 
for (int i = 0; i < 3; i++){ 
     ss >> vertexIndex[i] >> throwaway >> uvIndex[i] >> throwaway >> normalIndex[i]; 
}

我的下一个问题是为什么下面的不工作?

ss.ignore(std::numeric_limits<std::streamsize>::max(), '/');
ss >> vertexIndex[i] >>  uvIndex[i] >>  normalIndex[i];