how to read multiple text files in c++?

This is my code for one file:

#include <fstream>
#include <string>
using namespace std;


int main()
{

fstream file;
string word0,word1,word2, filename1;

cout << "Please enter the 1st file: " << endl;
cin >> filename1;

// opening file
file.open(filename1.c_str());

// extracting lines from the file
while (file >> word)
{
// displaying content
getline(file, word);
cout << word << endl;
}

return 0;
}



Use functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

std::vector <std::string> read_words( const std::string& filename )
{
  ...
}

std::string ask_filename( const std::string& nth )
{
  ...
}

int main()
{
  auto words1 = read_words( ask_filename( "1st" ) );
  auto words2 = read_words( ask_filename( "2nd" ) );
  ...
}

Hope this helps.
> how to read multiple text files in c++?
Where are you getting the list of files from?
- the command line
- the user
- another file

To move that code to reading multiple files, the first thing to do is move the read a single file code into another function. That will help you focus on one issue at once in each function.

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
28
29
30
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void read_a_file(string filename) {
  string word;
  // opening file
  ifstream file(filename.c_str());

  // extracting lines from the file
  while (file >> word)
  {
    // displaying content
    getline(file, word);
    cout << word << endl;
  }
}

int main()
{
  string filename;
  ifstream file("list_of_files.txt");
  // extracting lines from the file
  while (file >> filename)
  {
    read_a_file(filename);
  }
  return 0;
}


hi,

Here i was trying to get files from user but i was trying to get input from command line.

Thanks.
So
1
2
3
4
5
int main ( int argc, char *argv[] ) {
  for ( int i = 1 ; i < argc ; i++ ) {
    read_a_file(argv[i]);
  }
}
Thank you Salem for your help.
Topic archived. No new replies allowed.