结构体数组,非常量大小

Array of structs, non constant size

本文关键字:常量 非常 数组 结构体      更新时间:2023-10-16

是否可以创建一个结构体数组,如果你需要改变数组的大小取决于正在使用的文件?

我创建了一个结构体数组,但是我从文件中填充了这个结构体。我需要根据文件的行数来设置数组的大小

----好吧,谢谢,这是我工作的一个副业项目,在学校没有使用向量----

由于您在学校没有学习过标准库,这里有一个演示如何使用标准库从文本文件创建行数组(std::vector),以及如何处理失败。

代码不是为了实用。对于实际代码,我只是使用一个循环,在每次迭代中,getlinepush_back在向量上。

希望这能给你一些方向上的想法,以及显示什么头需要什么。:)

#include <algorithm>
using std::copy;
#include <iostream>
using std::cout; using std::cerr; using std::istream;
#include <fstream>
using std::ifstream;
#include <stdexcept>
using std::exception; using std::runtime_error;
#include <stdlib.h>     // EXIT_xxx
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <iterator>
using std::back_inserter; using std::istream_iterator;
auto hopefully( bool const e ) -> bool { return e; }
auto fail( string const& message ) -> bool { throw runtime_error( message ); }
class Line
{
private:
    string  chars_;
public:
    operator string& () { return chars_; }
    operator string const& () const { return chars_; }
    //operator string&& () && { return chars_; }
    friend
    auto operator>>( istream& stream, Line& line )
        -> istream&
    {
        getline( stream, line.chars_ );
        hopefully( stream.eof() or not stream.fail() )
            || fail( "Failed reading a line with getline()" );
        return stream;
    }
};
void cppmain( char const filename[] )
{
    ifstream f( filename );
    hopefully( not f.fail() )
        || fail( "Unable to open the specified file." );
    // This is one way to create an array of lines from a text file:
    vector<string> lines;
    using In_it = istream_iterator<Line>;
    copy( In_it( f ), In_it(), back_inserter( lines ) );
    for( string const& s : lines )
    {
        cout << s << "n";
    }
}
auto main( int n_args, char** args )
    -> int
{
    try
    {
        hopefully( n_args == 2 )
            || fail( "You must specify a (single) file name." );
        cppmain( args[1] );
        return EXIT_SUCCESS;
    }
    catch( exception const& x )
    {
        cerr << "!" << x.what() << "n";
    }
    return EXIT_FAILURE;
}