2013-04-11 9 views
0

我是C++的新手,從文本文件讀取數據行時遇到了一些麻煩。假設我在文本文件中有未知數的行,每行的格式都是相同的:int string double。唯一可以確定的是空間將分隔給定行上的每一條數據。我正在使用結構數組來存儲數據。下面的代碼很好,除了在每個循環之後跳過一行輸入。我試過插入各種ignore()語句,但仍然無法讀取每行,只讀其他行。如果我在最後重寫了一些getline語句,那麼在第一次循環之後,將開始爲變量存儲錯誤的數據。當讀取和存儲文件中的數據時,其他每行數據都會被跳過

文本文件可能是這樣的:

18 JIMMY 71.5 
32 TOM 68.25 
27 SARAH 61.4 


//code 
struct PersonInfo 
{ 
    int age; 
    string name; 
    double height; 
}; 
//..... fstream inputFile; string input; 

PersonInfo *people; 
people = new PersonInfo[50]; 

int ix = 0; 
getline(inputFile, input, ' '); 
while(inputFile) 
{ 
    people[ix].age = atoi(input.c_str()); 
    getline(inputFile, input, ' '); 
    people[ix].name = input;  
    getline(inputFile, input, ' '); 
    people[ix].height = atof(input.c_str()); 

    ix++; 

    getline(inputFile, input, '\n'); 
    getline(inputFile, input, ' '); 
} 

我敢肯定有更先進的方法可以做到這一點,但就像我說的,我很新的C++所以如果有隻是稍作修改到上面的代碼,那會很棒。謝謝!

+0

我讀到了全線然後解析行成翹楚領域。 – John3136 2013-04-11 02:12:56

回答

1

您可以執行文件讀取,如下所示:

int ix = 0; 
int age = 0; 
string name =""; 
double height = 0.0; 
ifstream inputFile.open(input.c_str()); //input is input file name 

while (inputFile>> age >> name >> height) 
{ 
    PersonInfo p ={age, name, height}; 
    people[ix++] = p; 
} 
+0

這個設置實際上工作。謝謝! – 2013-04-11 02:38:01

+0

@DawgPwnd歡迎您。 – taocp 2013-04-11 02:52:18

1

你所做的這整個代碼可笑的複雜。

struct PersonInfo 
{ 
    int age; 
    string name; 
    double height; 
}; 

std::vector<PersonInfo> people; 
PersonInfo newPerson; 
while(inputFile >> newPerson.age >> newPerson.name >> newPerson.height) 
    people.push_back(std::move(newPerson)); 

你的問題是,因爲首先你在同一時間從文件中再次讀取數據的一個的每一位,從格蘭文件,然後一整行,然後每一個數據位從文件的時間。也許你的意圖更像這樣?

std::string fullline; 
while(std::getline(inputFile, fullline)) { 
    std::stringstream linestream(fullline); 
    std::getline(linestream, datawhatever); 
    .... 
} 

順便說一句,更地道的代碼可能看起來更像是這樣的:

std::istream& operator>>(std::istream& inputFile, PersonInfo& newPerson) 
{return inputFile >> newPerson.age >> newPerson.name >> newPerson.height;} 

{ //inside a function 
    std::ifstream inputFile("filename.txt"); 

    typedef std::istream_iterator<PersonInfo> iit; 
    std::vector<PersonInfo> people{iit(inputFile), iit()}; //read in 
} 

Proof it works here

+0

不幸的是,我還沒有學習關於stringstream的知識,這個問題在沒有它的情況下是可以解決的。我相信我會學到很多能夠簡化我的代碼的東西,但現在我幾乎堅持已經列出的內容。載體解決方案看起來很有趣,所以我打算給這個鏡頭。 – 2013-04-11 02:24:47

+0

@DawgPwnd:如果你對stringstream不熟悉,那麼第一部分代碼就是你要找的東西。 – 2013-04-11 03:55:44

相關問題