0

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

(标签) (bin):(value) (bin):(value) 等

像:

-1 5:0.015748 6:0.0393701 8:0.0393702 12:0.0.09448811:0.09448214:0.09448212:0.09448812:0.094488

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

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

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' );
  } 
}

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

上面示例行的输出是:

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

接下来的所有行都会发生同样的事情。

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

4

1 回答 1

0

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

我的测试程序:

#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';
    }
}

该程序的输出是:

-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

因此,请确保变量类型正确,并更改循环以不得到双尾行。

于 2012-10-12T10:06:29.473 回答