// reading a text file
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string line;
ifstream myfile ("names.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
}
myfile.close();
}
else cout << "Unable to open file";
//std::string s
char *a=newchar[line.size()+1];
a[line.size()]=0;
memcpy(a,line.c_str(),line.size());
cout << a << endl;
char data [] = a;
cout << data[] <<endl;
system("PAUSE");
}
I already tried to convert it into char [] with a variable. And when I try to print out "a", it can print. But when I try to assign it into char data [] = a, it throw me error
Error 1 error C2440: 'initializing' : cannot convert from 'char *' to 'char []'
.
does anyone know why it throw error? I'm really stuck with it. Help will be appreciated..
One thing is that brackets on line 27 are empty, which is wrong because a static array must have its length known at compile time. The cases where [] is allowed are the cases where its length can be deduced at compiled time. In your case a could be of any length.
Though even if you fixed that, it's just not allowed by c++ syntax. An array can only be initialized with { ... } syntax or a string literal. You'll have to use memcpy here.
Though I don't see why you would want to do this at all..