using a vector and fstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <stdio.h>
#include <vector>
#include <fstream>
using namespace std;

int main() {
	vector<string> filenames;
	string file = "test_file.txt";
    filenames.push_back(file);

    for(int i=0; i<filenames.size(); i++){
    	fstream file_open(filenames[i]);
    }
	return 0;
}


it says no matching call for fstream

but when I just put fstream file_open("test_file.txt") it works!

Why is this??
Last edited on
In C++98 (from 1998) the constructor for std::fstream accepts a const char *, not an std::string.

This was amended in C++11 (from 2011).

What this means: your code will compile fine with a compiler that is recent enough.

http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream

Edit: otherwise, simply use std::string::c_str():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <stdio.h>
#include <vector>
#include <fstream>
using namespace std;

int main() {
	vector<string> filenames;
	string file = "test_file.txt";
    filenames.push_back(file);

    for(int i=0; i<filenames.size(); i++){
    	fstream file_open(filenames[i].c_str());
    }
	return 0;
}
Last edited on
Topic archived. No new replies allowed.