2012-10-12 40 views
0

我想在一个特征向量文件存储的特征向量以下列方式为:Istringstream不循行“走”

(标签)(BIN):(值)(BIN ):(值)等

像:

-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,如果该事项反正英寸

+0

一件事(无关你的问题虽然)是,你不应该使用',而(readFile.eof())'(或其他状态功能)。相反,'while(getline(readFile,line))'。 –

+0

顺便说一句,你能请编辑您的问题,包括label','bin','small_char'和'value'的'的声明。 –

+0

@JoachimPileborg'getline'在文件中,而不是'cin'。他只是从'cin'读取暂停。 –

回答

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 

所以一定要确保变量类型是否正确,并更改循环,从而不能获得双倍的最后几行。

+0

(函数getline(READFILE,线)'。我用一个字符串变量类型small_char,这是错误发生我想在那里。问题解决了 – user1435395