I would like to open from a file and then store the strings stored in the txt filed to an array.The txt file i want to open has 1 string on each line.So each line will be 1 string.What should i change here?

// 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 (! myfile.eof() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
getchar();
  return 0;
}

Recommended Answers

All 7 Replies

Before the reading look do a std::vector<std::string> fileContents. Then when you do each line do a fileContents. push_back( line ); Also. You can just do a while( getline(fileStream,line) ) { /*...*/ } instead of the .eof that you did.

I am a starter....Can u show me in code how to achieve this?Thx in advance.Btw i dont know sth about "vector".

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

int main () {
  string line;
  vector<string> file;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while (getline(myfile,line) )
    {
      file.push_back( line );
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  // Can print out: file[3], etc. To get th enumber of lines use file.size()
getchar();
  return 0;
}
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main () {
  string line;
  vector<string> file;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while (getline(myfile,line) )
    {
      file.push_back( line );
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  // Can print out: file[3], etc. To get th enumber of lines use file.size()
getchar();
  return 0;
}

I put the added lines in red.

edit: Whoops. Clearly I double posted. I meant to edit. but I hit reply.

And my array now is file[] which has file.size number of lines?

If you want an array you need knowledge of the number of lines in the file. The benefit of vectors is that you don't need knowledge, a priori (sp?), of the number of lines in the file. You can just add.

Otherwise you could just create a large array and add elements to that array...

sttring file[numLines];
int i(0);

while ( getline(file,line) )
  file[i++] = line;

Something like that.

Where can i read about teh functions above?I searched over the net but didnt find any explanatory guide...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.