C ++中的readline?

时间:2014-09-24 22:35:56

标签: c++ readline

我有一个文本文件,我需要在我的代码中读入变量。例如,假设.txt文件如下:

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 ++中重新创建它?

1 个答案:

答案 0 :(得分: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';
    }
}