繁体   English   中英

如何通过C ++解析文本文件?

[英]How to parse through a text file c++?

我正在尝试通过文本文件进行解析。 我正在用空格分隔单词之间。 这是文本文件的外观。

123456789 15.5 3 40.0

这种格式大约有15行。 现在使用

int sin = stoi(line.substr(0, line.find(' ')));

我可以将前两个字分开,但不能分开吗?

    const char * IN_FILE = "EmployeePayInput.txt";

    // A second way to specify a file name:
    #define OUT_FILE "EmployeePayOutput.txt"

 int main()
    {


ifstream ins;
        ins.open(IN_FILE);
        //Check that file opened without any issues
        if (ins.fail())
    {
        cerr << "ERROR--> Unable to open input file : " << IN_FILE << endl;
        cerr << '\n' << endl;
        _getch(); // causes execution to pause until a char is entered
        return -1; //error return code
    }

    //Define ofstream object and open file
    ofstream outs;
    outs.open(OUT_FILE);

    //Check that file opened without any issues
    if (outs.fail())
    {
        cerr << "ERROR--> Unable to open output file : " << OUT_FILE << endl;
        cerr << '\n' << endl;
        _getch(); // causes execution to pause until a char is entered
        return -2; //error return code
    }

    // Process data until end of file is reached
    while (!ins.eof()) {
        string line;


        while (getline(ins, line)) {
            Employee e;


            int sin = stoi(line.substr(0, line.find(' ')));//prints and stores the first item in sin
            e.setSin(sin);
            cout << sin << endl;
            float hourly = stof(line.substr(line.find(' ')));
            cout << hourly << endl;//prints and stores the second item in hourly
            e.setPayRate(hourly);
            int exemption = stof(line.substr( line.find(' '))); //doesn't do anything, I need to read the next item in the same line
                cout << exemption << endl;

        }
    }


    // Close files
    ins.close();
    outs.close();

    cout << '\n' << endl;

    // Remove following line of code (and this comment) from your solution
    cout << "Type any key to continue ... \n\n";

    _getch(); // causes execution to pause until char is entered
    return 0;
}

我将这样重写您的输入逻辑:

// Process data until end of file is reached
string line;
while (getline(ins, line)) {
    std::istringstream iss(line);
    if (iss >> sin >> hourly >> exemption) {
        Employee e;
        e.setSin(sin);
        e.setPayRate(hourly);
        cout << exemption << endl;
    }
}

对于您的特定问题, line.substr(line.find(' ')从第一个' '的位置获取其余行。此操作不会更改该line ,因此调用它会得到相同的结果第二次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM