Link to home
Start Free TrialLog in
Avatar of VDOGamer
VDOGamer

asked on

How to read in newline or null-terminated words into a cstring array

Hello, I was wondering what would be a better technique to read in a file of newline-terminated words and place them into an array of cstrings.  Do I have to read in each word char by char?

E.g.
The text file is as such:

car
apple
cities
ladies
Corvette


 Say I create a struct to hold the char array:

struct HoldTheChars
{
   char chArray[30];
};

...and I create an array of Type "HoldTheChars"

HoldTheChars strArray[45];

... and then use a double for-loop to fill in the array.
Is this the most efficient way?

Basically, I'd like to read in each word, as a cstring, and place it in an array, for future tests on how to search, binary or hashing.

Avatar of Jase-Coder
Jase-Coder

you could do

ifstream F

while(!F.feof())
  f.getline(Buffer[i++], 200);


something along thoselines
#include <stdio.h>
#include <string>
#include <iostream.h>
#include <fstream.h>


void main()
{      
      //Variables
      std::string str[100];
      char temp[1024];
      int i=0;
      ifstream fin;

      //Open up a file called test.txt for reading
      fin.open("test.txt", ios::in);


      //Read test.txt until end of file has been reached
      //Reads a line until 1024 characters have been read
      //or until the newline character has been read.  Then
      //stores that word (or words) in a string.
      while(!fin.eof())
      {
            fin.getline(temp, 1024, '\n');
            str[i++]=temp;
      }

      return;
}
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>


void main()
{      
      //Variables
      char str[100][100];
      int i=0;
      ifstream fin;

      //Open up a file called test.txt for reading
      fin.open("test.txt", ios::in);


      //Read test.txt until end of file has been reached
      //Reads a line until 100 characters have been read
      //or until the newline character has been read.
      while(!fin.eof())
      {
            fin.getline(str[i++], 100, '\n');
            printf("%s", str[i-1]);
      }

      return;
}
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I forgot a

    ifs.close()

in the first sample. In the second sample I need to access the struct member

    while (i < sizeof(strArray)/sizeof(HoldTheChars) && 
               ifs.getline(strArray[i].chArray, sizeof(HoldTheChars)) )
    ..

Regards, Alex