Rext Rext - 1 month ago 8
C++ Question

C++ Output text file data to char array

Simply put I need a program that reads a text file and puts all the data from the text file into and array.

I know you can output/read a text file with

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
string line;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}


What I need however is something that can take a text file...

EX:
Answers.txt

A
B
C
C
D
B
A
B


And outputs the data to an array.

End result should be something like....

char answers[] = [A, B, C, C, D, B, A, B];


Thanks for any and all help!

Answer

You can use a vector to add your lines.

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main () 
{
  string line;
  vector<string> lines;
  ifstream myfile ("numbers.txt");

  if (myfile.is_open())
  {
    while (! myfile.eof() )
    {
      getline (myfile,line);
      lines.push_back(line);
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  for (unsigned i = 0; i < lines.size(); ++i)
    cout << lines[i] << endl;

  return 0;
}

If you want more infos on a vector:

http://en.cppreference.com/w/cpp/container/vector http://www.cplusplus.com/reference/vector/vector/?kw=vector

Edit: Okay so if I understand, you need that:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  string line;
  string file;
  char *str;

  ifstream myfile ("numbers.txt");

  if (myfile.is_open())
  {
    while (! myfile.eof() )
    {
      getline (myfile,line);
      file += line; // Concatenate every lines
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  str = file.c_str(); // str contain the file as an array of char, without the newline char

  return 0;
}