2014-09-24 31 views
1

我有一個文本文件,我需要讀入我的代碼中的變量。例如可以說.txt文件看起來像:readline in C++?

John 
Town 
12 
Mike 
Village 
22 

在有名稱的圖案,然後再解決多歲的人。我發現,(`

string line; 
ifstream myfile ("example.txt"); 
if (myfile.is_open()) 
{ 
    while (getline (myfile,line)) 
    { 
     cout << line << '\n'; 
    } 
    myfile.close(); 
} 

我可以打印出的文本文件的每一行,但我怎麼能分配文本變量? 我記得在Java中,你可以沿着

while(there is a next line){ 
    name = something.readline(); 
    address = something.readline(); 
    age = something.readline(); 
    //do something with variables i.e construct new object then 
    //re-loop to construct new object with next set of data 
} 

的伎倆的線做一些事情是的ReadLine()被調用後,它會再向下移動一行在文本文件,然後下一個變量將被分配給下面的文字等等。我如何在C++中重新創建它?

+0

「的std :: string的姓名,地址,年齡;」 'getline(myfile,name);' 'getline(myfile,address);' 'getline(myfile,age);' – 2014-09-24 22:40:22

回答

0

當我做這樣的東西,我喜歡我的數據結構爲記錄和寫一個函數來讀取每個記錄,而像這樣:

// logically grouped data 
struct record 
{ 
    std::string name; 
    std::string address; 
    unsigned age; 
}; 

// function to read in one record 
// returns std:ostream& so that the while() loop can check 
// the stream to make sure the read was successful. 
// Takes record as a reference to pass the data back out 
// of the function 
std::istream& read(std::istream& is, record& r) 
{ 
    std::getline(is, r.name); 
    std::getline(is, r.address); 
    is >> r.age >> std::ws; 
    return is; 
} 

int main() 
{ 
    std::ifstream myfile("example.txt"); 

    record r; 

    while(read(myfile, r)) // while the read was a success 
    { 
     // do something with record here 
     std::cout << " name: " << r.name << '\n'; 
     std::cout << "address: " << r.address << '\n'; 
     std::cout << " age: " << r.age << '\n'; 
     std::cout << '\n'; 
    } 
}