Istringstream 不"walk"通过线路

Istringstream doesn't "walk" through the line

本文关键字:线路 walk Istringstream      更新时间:2023-10-16

我正在尝试通过以下方式读取存储特征向量的特征向量文件:

(标签) (垃圾箱):(值)

(垃圾桶):(值)等

喜欢:

-1 5:0.015748 6:0.0472441 7:0.0393701 8:0.00787402 12:0.0314961 13:0.0944882 14:0.110236 15:0.0472441 20:0.023622 21:0.102362

22:0.110236 28:0.015748 29:0.228346 30:0.125984

如您所见,它的保存没有值为 0 的箱。

我尝试使用以下代码读取它们:

int bin;
int label;
float value;
string small_char; -> change to char small_char to fix the problem
if(readFile.is_open())
  while(!readFile.eof()) {
    getline(readFile, line);
    istringstream stm(line);
    stm >> label;
    cout << label << endl;
    while(stm) {
          stm >> bin;
          stm >> small_char;
          stm >> value;
          cout << bin << small_char << value << endl;
    }
    cout << "Press ENTER to continue...";
    cin.ignore( numeric_limits<streamsize>::max(), 'n' );
  } 
}

但是由于未知原因,标签被正确读取,第一个有值的箱也被读取,但下面的箱根本没有被读取。

上述示例行的输出为:

-1
5:0.015748
5:0.015748
Press ENTER to continue

后面的所有行都会发生同样的事情。

我正在使用Visual Studio 10,如果这很重要的话。

自己测试过后,似乎您没有使用正确的类型(以及正确的循环条件)。

我的测试程序:

#include <sstream>
#include <iostream>
int main()
{
    std::istringstream is("-1 5:0.015748 6:0.0472441 7:0.0393701 8:0.00787402 12:0.0314961 13:0.0944882 14:0.110236 15:0.0472441 20:0.023622 21:0.102362 22:0.110236 28:0.015748 29:0.228346 30:0.125984");
    int label;
    int bin;
    char small;
    double value;
    is >> label;
    std::cout << label << 'n';
    while (is >> bin >> small >> value)
    {
        std::cout << bin << small << value << 'n';
    }
}

该程序的输出是:

-15:0.0157486:0.04724417:0.03937018:0.0078740212:0.031496113:0.094488214:0.11023615:0.047244120:0.02362221:0.10236222:0.11023628:0.01574829:0.22834630:0.125984

因此,请确保变量类型正确,并将循环更改为不获取倒数双行。