结构体数组,非常量大小
Array of structs, non constant size
是否可以创建一个结构体数组,如果你需要改变数组的大小取决于正在使用的文件?
我创建了一个结构体数组,但是我从文件中填充了这个结构体。我需要根据文件的行数来设置数组的大小
----好吧,谢谢,这是我工作的一个副业项目,在学校没有使用向量----
由于您在学校没有学习过标准库,这里有一个演示如何使用标准库从文本文件创建行数组(std::vector
),以及如何处理失败。
代码不是为了实用。对于实际代码,我只是使用一个循环,在每次迭代中,getline
和push_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;
}
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性