如果需要根据正在使用的文件更改数组的大小,是否可以创建一个结构数组?非常数大小的结构数组
我创建一个结构数组,但即时填充从一个文件的结构。我需要根据文件中有多少行来制作数组的大小。
----好感谢,其方项目IM工作,在学校.----
如果需要根据正在使用的文件更改数组的大小,是否可以创建一个结构数组?非常数大小的结构数组
我创建一个结构数组,但即时填充从一个文件的结构。我需要根据文件中有多少行来制作数组的大小。
----好感谢,其方项目IM工作,在学校.----
因为我们还没有从学校里了解到的标准库,这里有一个演示没有使用矢量如何使用标准库创建来自文本文件的行数组(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;
}
匿名downvoter:如果你愿意解释你的downvote,它会帮助别人(要么理解你的洞察力,要么更容易忽略你)。就目前来看,这是一个年轻孩子的交流。如何让它更成熟,说? –
使用'std :: vector'。 – DeiDei
矢量,维克多。 – nicomp
*并没有在学校使用矢量* - 这是如何在学校教C++的悲哀形式。 – PaulMcKenzie