简体   繁体   English

在C ++中从具有整数和字符串的文本文件中读取数据的最佳方法是什么?

[英]What would be the best way to read data from a text file with ints and strings in c++?

For my comp sci class I had to create a program that (simply put) handles employees. 对于我的comp sci类,我必须创建一个(简单地说)处理员工的程序。 Up until this point I have had no issues. 到目前为止,我还没有任何问题。 However, the last part of the assignment is to "Create a Test Program that handles an array of 5 employees that are input from a text file and then output as an employee report to the screen." 但是,分配的最后一部分是“创建一个测试程序,该程序处理从文本文件输入的5个雇员的数组,然后将其作为雇员报告输出到屏幕上。” I thought this would be relatively easy, after all, how hard is it to parse a text document. 我认为这毕竟相对容易,毕竟解析文本文档有多难。 The problem is that I need to input both strings and ints and they are not in any kind of simple pattern or separation. 问题是我需要同时输入字符串和整数,并且它们不是任何简单的模式或分隔符。 The function that I have to input data to looks like this: 我必须输入数据的功能如下所示:

void employeeType::setEmployeeType(string first, string middle, string last,
                               int month, int day, int year, int ID,
                               string street, string town, string state, int zip, string county, string country,
                               int home, int cell, string email,
                               int sMonth, int sDay, int sYear,
                               string oStreet, string oTown, string oState, int oZip, string oCounty, string oCountry,
                               int work, int salary) {//code here..}

And one of my inputs from the text document: 我从文本文档中输入的内容之一是:

William, R, Smith, 8, 24, 1963, 555238911, 12345 Street1, State1, 77123, County1, Country1, 1112223333, 3332221111, email@email.com, 3, 19, 2007, 12345 oStreet1, oTown1, oState1, 77987, oCounty1, oCountry1, 2221113333, 75000

I was planning on separating each input by detecting every ", " which would end each input. 我打算通过检测将结束每个输入的每个“,”来分离每个输入。 I could always hard code it so that certain inputs (input numbers 4, 5, 6, 7, 10, 13, 14, 16, 17, 18, 22, 23, and 24) would be parsed as ints, but that would not look very good and there is probably a better way to do this. 我总是可以对其进行硬编码,以便将某些输入(输入数字4、5、6、7、10、13、14、16、17、18、22、23和24)解析为int,但这不会看起来非常好,也许有更好的方法可以做到这一点。 Does anyone have a suggestion? 有人有建议吗?

I can always provide whatever extra information is needed. 我随时可以提供所需的任何其他信息。

This solution define a new white-space that match on comas (,). 此解决方案定义了一个与逗号(,)相匹配的新空白。 I also define a data structure, but that is optional. 我还定义了一个数据结构,但这是可选的。 Finally, it use the ifstream stream to get data inside the structure. 最后,它使用ifstream流在结构内部获取数据。

More info in the following text: http://en.cppreference.com/w/cpp/locale/ctype_char 以下文本提供了更多信息: http : //en.cppreference.com/w/cpp/locale/ctype_char

#include <iostream> //to output results
#include <vector>   //for the whitespace
#include <fstream>  //to open the file
#include <string>   //strings
using namespace std;//Avoid that in real projects

// Define a new type of white-space that mach comas (,)
struct my_whitespace : std::ctype<char> 
{
    static const mask* make_table()
    {
        // make a copy of the "C" locale table
        static std::vector<mask> v(classic_table(),  
            classic_table() + table_size);
        // these will be whitespace
        v[','] |=  space; 
        // space and tab won't be whitespace
        v[' '] &= ~space;
        v['\t'] &= ~space;
        return &v[0];
    }
    my_whitespace(std::size_t refs = 0) :
        std::ctype<char>(make_table(), false, refs) {}
};

// Data structure to save each line of the file (optional)
struct Data
{
    string first;
    string middle; 
    string last;
    int month; 
    int day; 
    int year; 
    int ID;
    string street; 
    //...
};

// Main function, in real project, get that outside the main.    
int main()
{
    // Open the file
    ifstream file ("file.txt", ios::in);
    // Set the white-space to mache comas
    my_whitespace *ws = new my_whitespace();
    file.imbue( std::locale(file.getloc(), ws));
    if (file.is_open())
    {
        Data d;
        // For each line of the file
        while (file)
        {
            char s; // To skip the first space after the coma.
            // Read one line of the file.
            file >> 
                d.first >> 
                s >> d.middle >> 
                s >> d.last >> 
                s >> d.month >> 
                s >> d.day >> 
                s >> d.year >> 
                s >> d.ID >> 
                s >> d.street //>>
                /*...*/
                ;
            // Print the result (optional)
            cout << d.first << endl;
            cout << d.middle << endl;
            cout << d.last << endl;
            cout << d.month << endl;
            cout << d.day << endl;
            cout << d.street << endl;
            //...
        }
    }
    file.close(); // This function delete ws
    // delete ws;

    return 0;
}

Note: Careful with comas inside a string field. 注意:小心字符串字段内的逗号。

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

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