File names as mapped values.

Im trying to make a map such that i can access text files, using i/ostream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
int main()
{
std::string input = "input.txt";
  ofstream myfile;
  myfile.open (input);
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}


Ive tried a couple of variations to this but cant seem to get it to work.
Oh i just realized that code isnt the right one heres the right code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
int main()
{
  map<string, const char*> myMap;
  myMap["input"] = "input.txt";
  ofstream myfile;
  myfile.open (myMap.find("input"));
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
Last edited on
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 <string>
#include <iostream>
#include <fstream>
#include <map>
using namespace std;

int main()
{
  // map<string, const char*> myMap;
  std::map< std::string, std::string > myMap; // safer to store a copy of the path

  myMap["input"] = "input.txt";

  // ofstream myfile;
  // myfile.open (myMap.find("input"));
  // myfile << "Writing this to a file.\n";
  auto iterator = myMap.find("input") ; // find returns an iterator
  if( iterator != myMap.end() ) // if we have found it
  {
      std::ofstream myfile( iterator->second ) ; // C++11
      // std::ofstream myfile( iterator->second.c_str() ) ; // C++98
      myfile << "Writing this to a file.\n";
  }

  // myfile.close();
  // return 0;
}
Thanks.
Topic archived. No new replies allowed.