如何从文件中读取单独的行?

时间:2014-01-19 14:51:22

标签: c++ fstream ifstream

------------------------------------------------
          Artiles for a magazine          
------------------------------------------------
There are total 5 articles in the magazine
------------------------------------------------
ID : 3
Description : opis2
Price : 212
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 424
Date : 20324
------------------------------------------------
ID : 3
Description : 54
Price : 123
Incoming amount : 12
Outgoing amount : 0
Taxes : 0
Total : 1476
Date : 120915
------------------------------------------------
ID : 3
Description : opsi2
Price : 12
Incoming amount : 324
Outgoing amount : 0
Taxes : 0
Total : 3888
Date : 570509
------------------------------------------------
ID : 2
Description : vopi
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 951230
------------------------------------------------
ID : 1
Description : opis1
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 101
------------------------------------------------

我有一个名为directory.dat的文件,其中包含上述内容。我想要做的是以下几点。

我想查找给定年份中具有相同ID的所有文章,并执行以下操作:传出金额 - 传入金额。所以,我的问题是如何通过使用该文件找到给定年份(由用户)具有相同ID的所有文章,并为它们执行传出金额 - 传入金额?

我试过这样的事情:

ifstream directory("directory.dat");
//directory.open("directory.dat");
string line;
string priceLine = "Price : ";
int price;
while(getline(directory, line)){
    if(line.find(priceLine) == 0){
        cout << atoi(line.substr(priceLine.size()).c_str()) << endl;
    }
}
cout << price << endl;
directory.close();

但我远离正确的轨道,我需要一些帮助来实现这样的目标。

1 个答案:

答案 0 :(得分:2)

您需要定义精确输入的格式(可能是BNF语法)。一个例子是不够的。我们无法猜测Artiles for a magazine是否有意义。

 while(getline(directory, line)){
    int colonpos = -1;
    if (line.find("----")) {
        /// check that line has only dashes, then
        process_dash_line();
    }
    else if ((colonpos=line.find(':'))>0) {
       std::string name = line.substr(0, colonpos-1);
       std::string value = line.substr(colonpos+1);
       process_name_value (name, value);
    }
 }

此外,研究(并且可能适应)JSON(例如jsoncpp)和YAML(例如yaml-cpp)的一些免费软件C ++解析器的源代码。他们肯定会给你一些启发。

了解有关C ++标准库的更多信息,例如:在cppreference.com&amp; cplusplus.com(这两个网站都很容易阅读但不完善)当然还有阅读C++11标准,或者至少是草案n3337