2016-10-28 3 views
-4

사용중인 파일에 따라 배열의 크기를 변경해야하는 경우 구조체 배열을 만들 수 있습니까?구조체 배열, 고정 크기가 아닌

구조체의 배열을 만드는 중이지만 파일에서 구조체를 채우는 중입니다. 내가 파일의 몇 줄에 따라 배열의 크기를 만들 필요가있다.

---- 네 덕분에, 자사의 사이드 프로젝트 메신저가 작동 학교 .----

당신이 학교에서 표준 라이브러리에 대해 배웠하지 않았으므로
+9

'std :: vector'를 사용하십시오. – DeiDei

+3

Vector, Victor. – nicomp

+4

* 학교에서 벡터를 사용하지 않았습니다. * 이것은 학교에서 C++을 가르치는 방식의 슬픈 모양입니다. – PaulMcKenzie

답변

-1

, 여기 데모의에서 벡터를 사용하지 않은 표준 라이브러리를 사용하여 텍스트 파일의 행 배열 (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; 
} 
+0

익명 downvoter : 당신 ** downvote ** **를 설명한다면 그것은 다른 사람들을 (당신의 통찰력을 이해하거나 더 쉽게 무시할) 도울 것입니다. 현재 어린 아이의 의사 소통입니다. 어른을 더 어른으로 만드는 건 어때? –

관련 문제