Converting string of text file into char []

Hi.
I try to convert string of text file into char[]. And below is the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace 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=new char[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..

Thanks...^^
Last edited on
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..
Topic archived. No new replies allowed.