c ++逐行读取文本文件到结构数组中的char数组

时间:2014-03-17 00:25:15

标签: c++ arrays structure line-by-line filestreams

我是C ++的新手,在理解整个文件流的过程中遇到了一些麻烦......任何帮助都会受到赞赏......这就是我遇到麻烦的地方

我有一系列像这样的结构; (不,我不允许使用字符串来显示这些东西,或者矢量或任何其他更高级的东西我还没有覆盖)...

struct Staff
{
    char title[TITLESIZE];
    char firstName[NAMESIZE];
    char familyName[NAMESIZE];
    char position[POSSIZE];
    char room[TITLESIZE];
    char email[POSSIZE];
};

然后我有一个这些结构的数组;

Staff record[MAXNOSTAFF];

数据包含在由制表符分隔的文本文件中。但是某些字段可能包含空格。 数据如下:

Dr Sherine ANTOUN Lecturer 4327 3.204 sherine_antoun@gmail.com

以下是我在代码中写的内容......

//function prototypes
bool getRecord (ifstream& infile, Staff dataAr[], bool& fileFound);

int main()
{

    Staff record[MAXNOSTAFF];
    bool fileFound;
    ifstream infile;

    getRecord(infile, record, fileFound); //function call
    if (fileFound==true) 
    {
        cerr <<"Exiting Program"<<endl;
        exit(1);
    }

    return 0;
}

//function definitions
bool getRecord (ifstream& infile, Staff dataAr[], bool& fileFound)
{
    infile.open("phonebook.txt");

    if (infile)
    {
        fileFound = true;
        cout << "File " <<PHONEBOOK<< " opened successfully.\n\n";
    }
    else if (!infile)
    {
        fileFound =  false;
        cerr << "Error! File could not be opened. \n";
    }

    while (infile.good())
    {        

        for (int lineIndex=0; lineIndex<MAXNOSTAFF; lineIndex++)
            for (int titleIndex=0; titleIndex<TITLESIZE; titleIndex++)
            {
                cin.getline(dataAr[lineIndex].title[titleIndex], MAXNOSTAFF, '/t');
            }

    }
    //check it works properly
    for (int k=0;k<10; k++)
    {
        for (int m=0; m<11; m++)
        {
            cout << k <<". Title is : "<<dataAr[k].title[m]<<endl;
        }
    }    
    infile.close();
    return fileFound;
}

非常感谢任何帮助..谢谢

2 个答案:

答案 0 :(得分:2)

让我向您展示解析输入数据的Boost Spirit方法。

如果你从像

这样的结构开始
struct Staff
{
    std::string title;
    std::string firstName;
    std::string familyName;
    std::string position;
    std::string room;
    std::string email;
};

您可以使用Spirit语法,如:

    column = lexeme [ *~char_("\t\r\n") ];
    start  = column >> '\t'  >> column >> '\t' >> column >> '\t' >> column >> '\t' >> column >> '\t' >> column;

将所有行解析为如下的向量:

    It f(std::cin), l;
    std::vector<Staff> staff_members;
    bool ok = qi::parse(f, l, grammar % qi::eol, staff_members);

    if (ok)
    {
        for(auto const& member : staff_members)
        {
            std::cout << boost::fusion::as_vector(member) << "\n";
        }
    } else
    {
        std::cout << "Parsing failed\n";
    }

    if (f != l)
        std::cout << "Remaining input '" << std::string(f, l) << "'\n";

以下是完整的测试计划 Live on Coliru ,示例运行:

clang++ -std=c++11 -Os -Wall -pedantic main.cpp && ./a.out <<INPUT
Dr  Sherine ANTOUN  Lecturer    4327    3.204   sherine_antoun@gmail.com
Mr  Jason SCRYPT    Enthusiast  3472    9.204   jason_scrypt@yahoo.com
INPUT

输出:

(Dr Sherine ANTOUN Lecturer 4327 3.204 sherine_antoun@gmail.com)
(Mr Jason SCRYPT Enthusiast 3472 9.204 jason_scrypt@yahoo.com)
Remaining input '
'

完整列表

#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/tuple/tuple_io.hpp>

namespace qi = boost::spirit::qi;

struct Staff
{
    std::string title;
    std::string firstName;
    std::string familyName;
    std::string position;
    std::string room;
    std::string email;
};

BOOST_FUSION_ADAPT_STRUCT(Staff, 
    (std::string, title)
    (std::string, firstName)
    (std::string, familyName)
    (std::string, position)
    (std::string, room)
    (std::string, email))

template <typename It, typename Skipper = qi::unused_type>
    struct grammar : qi::grammar<It, Staff(), Skipper>
{
    grammar() : grammar::base_type(start)
    {
        using namespace qi;
        column = lexeme [ *~char_("\t\r\n") ];
        start  = column >> '\t'  >> column >> '\t' >> column >> '\t' >> column >> '\t' >> column >> '\t' >> column;
    }
    private:
    qi::rule<It, std::string(), Skipper> column;
    qi::rule<It, Staff(), Skipper> start;
};

int main()
{
    std::cin.unsetf(std::ios::skipws);

    typedef boost::spirit::istream_iterator It;
    grammar<It> grammar;

    It f(std::cin), l;
    std::vector<Staff> staff_members;
    bool ok = qi::parse(f, l, grammar % qi::eol, staff_members);

    if (ok)
    {
        for(auto const& member : staff_members)
        {
            std::cout << boost::fusion::as_vector(member) << "\n";
        }
    } else
    {
        std::cout << "Parsing failed\n";
    }

    if (f != l)
        std::cout << "Remaining input '" << std::string(f, l) << "'\n";
}

答案 1 :(得分:1)

由于您无法使用std::stringstd::vectorsscanf()可能是您的选择:

    while (infile.good())
    {
        char line[BUF_SIZE];
        for (int lineIndex=0; lineIndex<MAXNOSTAFF; lineIndex++)
        {
            infile.getline(line, BUF_SIZE);
            sscanf(line, "%s %s %s %[^\t] %s %s", dataAr[lineIndex].title, dataAr[lineIndex].firstName, dataAr[lineIndex].familyName, dataAr[lineIndex].position, dataAr[lineIndex].room, dataAr[lineIndex].email);
        }
    } 

注意%[^\t]格式说明符,它将匹配不是\t的每个字符(因为^),以便可以正确读取包含空格的文件。我不知道哪些字段确实包含空格,所以我只想写一个例子 修改
如果允许使用std::stringstd::stirngstream,则可以在从文件流中获取一行后拆分字符串:

while (infile.good())
    {
        char line[BUF_SIZE];
        for (int lineIndex=0; lineIndex<MAXNOSTAFF; lineIndex++)
        {
            infile.getline(line, BUF_SIZE);
            stringstream ss(line);
            std::string s;
            getline(ss, s, '\t'); // get the first field

            getline(ss, s, '\t'); // get the second field

            // ...
        }
    }