1

帐号类型 金额

15 检查 52.42

23 节省 51.51

11 检查 12.21

是我的制表符分隔文件

我希望能够按帐号搜索行。说如果我输入 23,我想得到那个特定的行。我会怎么做?

更先进的是,如果我想更改特定值,例如帐户 23 中的金额 51.51。我如何获取该值并将其替换为新值?

到目前为止,我只是逐行阅读

字符串线;ifstream is("account.txt");

 if (is.is_open())
 {
while (std::getline(is, line))  // read one line at a time
{
    string value;
    string parseline;
    std::istringstream iss(line);

    getline(line, parseline);
    cout << parseline << endl;  // do something with the value
    while (iss >> value)    // read one value at at time from the line
    {
        //cout << line << "   ";    // do something with the value
    }
}
is.close();
 }
 else
     cout << "File cant be opened" << endl;

return 0;
4

2 回答 2

2

鉴于每一行都是可变长度的,如果不首先解析整个文件,就无法索引特定行。

但我怀疑你的程序会想要操纵随机的行和列。所以我首先解析整个文件。将每一行放入数组中自己的数据结构中,然后在数组中索引该行。

您可以使用“strtok”将输入拆分为行,然后再次使用 strtok 将每行拆分为字段。

于 2012-07-26T19:16:56.963 回答
0

如果我要这样做,我会首先编写一些函数来解析整个文件并将数据存储在适当的数据结构中(例如数组或 std::map)。然后我会将数据结构用于所需的操作(例如搜索或编辑)。最后,如果有任何修改,我会将数据结构写回文件。

于 2012-07-26T19:54:36.137 回答