Storing txt file into a string array.

Mar 7, 2013 at 8:54pm
Does anybody know how to store txt data into a string array?
Im trying to store this into a string array of [6].

text.txt

sounds\\cde.wav
sounds\\door.wav
sounds\\water.wav
sounds\\crow.wav
sounds\\luke.wav
sounds\\welcome.wav
Mar 7, 2013 at 9:05pm
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
#include <iostream>
#include <fstream>
#include <string>

int main( int argc, char* argv[] )
{
  const int NUM_LINES = 6;
  std::fstream inFile;
  std::string lines[NUM_LINES];

  inFile.open( "file.txt" );

  if( !inFile )
  {
    std::cout << "Couldn't open file\n";
    return -1;
  }

  for( int i=0; i < NUM_LINES; ++i )
  {
    std::getline( inFile, lines[i] );
  }

  inFile.close();

  return 0;
}


I'd suggest using a vector rather than an array. It means you can add lines to the text file and they'll automatically get read in without having to alter the code.
Last edited on Mar 7, 2013 at 9:07pm
Topic archived. No new replies allowed.