+ 1
How to use user input with fstream im c++?
I'm working on a small log project and was wondering if its possible to use user input from cin in myfile.ope (file) I've tried and it throws errors. any suggestions???
4 Answers
+ 11
If you are talking about storing user input into text file, it's almost the same way, just get the user to cin to local variable and use ofstream object to write to text file.
+ 10
You need to use the ifstream object to do that.
#include <fstream>
using namespace std;
int main()
{
string str;
ifstream input; // or any name
input.open("sometext.txt");
input >> str; // gets one string
getline(input, str); // gets entire line into string
// etc
return 0;
}
+ 9
Oh, that's what you mean.
string filename;
ofstream file;
cin >> filename;
filename += ".txt";
file.open(filename.c_str());
// try if this works. Include <cstring> header for c_str() function which converts string to const char* data type.
I've just tested with C.Playground and no error was thrown. :>
+ 1
I'll try to explain better.
char x;
cin >> x;
ofstream myfile;
myfile.open(x)
this throws invalid char error
user input for the file name and dir.