2017-11-25 212 views
1

我有一個198(但它可以在任何點之間介於0-200)行的文件。我的文件的每一行如下所示:C++如何讀取文件,數值以逗號分隔

Urdnot Wrex,2.75,198846.13 
Urdnot Bakara,3,189484.84 
Hannah Shepard,1.75,188145.14 
David Anderson,2.25,182169.46 
Kasumi Goto,2.75,176795.83 

這是我的代碼,但它不想工作。

int index = 0; // The index of the file. 

while(index <= 200) { 
    in.ignore(256, ','); 
    in >> employeeName; 
    in.ignore(256, ','); 
    in >> employeeScore; 
    in.ignore(256, '\n'); 
    in >> employeeSalary; 

    cout << index << ": " << employeeName << ", " << employeeScore << ", " << employeeSalary << endl; 
    index++; 
} 

然而,與198行的文件,只與輸出中讀取3:

0: 2.75,198846.13, 3, 0 
1: 2.75,198846.13, 3, 0 
2: 2.75,198846.13, 3 

如果任何人有如何使它工作的任何想法,那將是非常讚賞。

回答

1

像這樣:

#include <fstream> 

std::ifstream infile("thefile.txt"); 
if (infile.is_open()) { 
    float number; 
    std::string str; 
    char c; 
    while (infile >> str >> >> c >> number && c == ',') 
     cout << number << " " << str << "\n"; 
} 
infile.close();