Hi iam new to c++ and iam trying out this vector program and i am getting the following error:
error: conversion from test*' to non-scalar typetest’ requested|
Here is the code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class test{
string s;
vector <string> v;
public:
void read(){
ifstream in ("c://test.txt");
while(getline(in,s))
{
v.push_back(s);
}
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<"\n";
}
}
};
int main()
{
cout<<"Opening the file to read and displaying on the screen"<<endl;
test t=new test();
t.read();
}
newis used to dynamically allocate memory. You don’t need to do that, so just do:The error is because the type of
new test()is atest*, a pointer to a (newly created)test. You can’t assign atest*to atest.The pointer version, for what it’s worth, would have been:
However, it’s bad style to do raw memory allocation like that. You’d use something called a smart pointer to make sure it gets deleted automatically, instead. The standard library has one in the header
<memory>, calledauto_ptr, that would suffice:However, all this isn’t needed for you, in this case. Always prefer automatic (stack) allocation over dynamic allocation.