C++读取TXT文档中最后一行中的数字并将其作为新的值加入后边新的运算

需要代码可以读取文本最后一行的数字,并将其加入到接来去的运算中去,有没有大神帮帮我

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

// 文本文件中的一行记录 
class Element
{
public:
    Element() : count(0) {}
    
    string id;         // ID 
    string name;   // 名称 
    long count;     // 数量 
};

int main()
{
    // 打开输入文件 
    ifstream infile("in.txt", ios::in);
    if(!infile)
    {
        // 打开文件错误 
        cerr << "Open File in.txt ERROR!" << endl;
        return 1;
    }
    
    vector<Element> data;        // 输入文本文件中的所有数据 
    
    // 读文件 
    string line;
    while(getline(infile, line)) // 读取一行记录 
    {
        Element e;
        stringstream ss;
        unsigned int from = 0, to = 0;
        
        // 截取 id 
        to = line.find(" ", from);
        e.id = line.substr(from, to - from);
        from = ++to;
        
        // 截取 name 
        to = line.find(" ", from);
        e.name = line.substr(from, to - from);
        from = ++to;
        
        // 截取 count 
        ss << line.substr(from);
        ss >> e.count;
        
        data.push_back(e);
    }
    infile.close();
    
    // 统计用户输入 
    while(true)
    {
        cout << "请输入编号,输入-1表示结束: ";
        string input;
        cin >> input;
        if(input == "-1")
        {
            // 结束 
            break;
        }
        
        // 查找对应的记录 
        int index;
        for(index = 0; index < data.size(); ++index)
        {
            if(input == data[index].id)
            {
                break;
            }
        }
        if(index == data.size())
        {
            // 未找到对应记录 
            cerr << "对不起,无此编号..." << endl;
            continue;
        }
        
        // 更新数量 
        ++data[index].count;
    }
    
    // 打开输出文件 
    ofstream outfile("out.txt", ios::out);
    if(!outfile)
    {
        // 打开文件错误
        cerr << "Open File out.txt ERROR!" << endl;
        return 1;
    }
    
    // 写文件 
    for(int i = 0; i < data.size(); ++i)
    {
        outfile << data[i].id << ' ' << data[i].name << ' ' << data[i].count << endl;
    }
    outfile.close();
    
    system("pause");
    return 0;
}

追问

只是要读取文档最后一行的数字,然后把它作为后边运算的数据而已。

温馨提示:答案为网友推荐,仅供参考
相似回答