헤더 파일은별로 좋지 않지만 헤더 파일을 사용하여 파일의 데이터를 읽고 기본 cpp 파일의 벡터로 데이터를 반환하려고합니다.C++ 헤더 파일에서 배열을 초기화하고 반환하는 방법은 무엇입니까?
#include <iostream>
#include <fstream>
#include "readposcar.h"
using namespace std;
int main(void) {
int nbasis = 2;
int nkpts = 10;
vector<double> myvec2(3);
myvec2 = add();
cout << "No. of k-points: " << nkpts << endl;
return 0;
}
이 분명히 작동하지 않습니다
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int add(void) {
double a1x, a1y, a1z, a2x, a2y, a2z, a3x, a3y, a3z; // I want all this stuff in vector form
int i;
double scale;
string line; stringstream dum;
ifstream poscar ("POSCAR");
for (i=1; i<=5; i++) {
getline(poscar,line);
if (i==2) {stringstream dum(line); dum >> scale;}
if (i==3) {stringstream dum(line); dum >> a1x >> a1y >> a1z;}
if (i==4) {stringstream dum(line); dum >> a2x >> a2y >> a2z;}
if (i==5) {stringstream dum(line); dum >> a3x >> a3y >> a3z;}
}
vector<double> myvec(3);
myvec[0] = a1x;
myvec[1] = a1y;
myvec[2] = a1z;
return myvec;
}
가 여기 내 .cpp 파일입니다 :
여기 내 readposcar.h 파일입니다. 누군가가 잘못된 것이 무엇인지와 내가 제대로 작동하도록하기 위해해야 할 일에 대해 조언 해 줄 수 있습니까? 나는 내가 .h 파일에서 myvec [2]라고 말하면서 전체 어레이가 아니라고 말할 때만 작동하도록 할 수 있습니다.
벡터가 작동하지 않는 경우 배열로 사용해도 괜찮습니다. 헤더 파일의 배열을 일종의 전역 배열로 초기화 한 다음 .cpp 파일에서 간단히 호출 할 수 있습니까? 파일에서
이 MAIN.CPP에서 포함 : 4 : 0 : 당신은 올바른 유형을 반환하지 않습니다
readposcar.h: In function ‘int add()’:
readposcar.h:27:9: error: cannot convert ‘std::vector<double>’ to ‘int’ in return
main.cpp: In function ‘int main()’:
main.cpp:12:15: error: no match for ‘operator=’ in ‘myvec2 = add()’
이것은 나를 위해 일했습니다. 빠른 답장을 보내 주셔서 감사합니다!. std :: vector add (void) { ... return myvec; } –
당신은 "using namespace std;"를 쓰는 것을 후회할 것입니다. 헤더 – doctorlove