How to read a .text file using c-strings?

advertisements

I'm working on a project for school and I need to read in text from a file.

Sounds easy peasy, except my professor put a restriction on the project: NO STRINGS ("No string data types or the string library are allowed.")

I've been getting around this problem by using char arrays; however, I'm not sure how to use char arrays to read in from a file.


This is an example from another website on how to read in a file with strings.

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

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

The important line here is while ( getline (myfile,line) );

getline accepts an ifstream and a string (not char array).

Any help is appreciated!


Use cin.getline. Refer to this site for the format: cin.getline.

You can write something like this:

ifstream x("example.txt");
char arr[105];
while (x.getline(arr,100,'\n')){
    cout << arr << '\n';
}