2014-09-24 67 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'; 
    } 
}