Reputation: 47
The basic syntax I use to write to a .txt file is this:
ofstream myfile;
myfile.open ("data.txt", ios::trunc);
outfile<<"writing";
Now, supposing i were to let the user decide which file should be accessed, could it be done through a string?
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ofstream myfile;
string filename;
char x;
cin>>x;
if (x==1)
filename="data2.txt";
myfile.open (filename, ios::trunc);
myfile<<"writing";
return 0;
}
I already tested this and it didn't work. My question is: is it possible to do such a thing? If yes, how? When i compile it, the error i get is the following:
undefined reference to 'std::basicofstream<char, std::char_traits<char> >::open(std::string const&, std::_Ios_Openmode)'
I can't understand what it is that's causing it.
Upvotes: 0
Views: 422
Reputation: 57728
Your error says it can't find open
method that uses std::string
.
Try this:
myfile.open(filename.c_str(), ios::trunc);
Some versions of C++ do not allow the std::string
for open
method, so you will have to use the c_str()
method of std::string
.
Upvotes: 2
Reputation: 44878
You should add an else
branch since if x
isn't equal to 1
open
has nothing to open.
Also you forgot to declare ofstream myfile;
in your second snippet. Maybe that's the reason this doesn't work (it shouldn't even compile).
Upvotes: 1