【问题标题】:readline in C++?C ++中的readline?
【发布时间】:2014-09-24 22:35:56
【问题描述】:

我有一个文本文件,需要将其读入代码中的变量。例如,假设.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++ 中重新创建它?

【问题讨论】:

  • 'std::string name, address, age;' 'getline(我的文件,名称);' 'getline(我的文件,地址);' 'getline(myfile, age);'

标签: c++ readline


【解决方案1】:

当我做这样的事情时,我喜欢将我的数据构造成记录并编写一个函数来读取每条记录,就像这样:

// 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';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多