+ 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???

2nd Apr 2017, 2:40 AM
Michael Darnell
Michael Darnell - avatar
4 Antworten
+ 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.
2nd Apr 2017, 2:54 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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; }
2nd Apr 2017, 2:52 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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. :>
2nd Apr 2017, 2:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
2nd Apr 2017, 2:56 AM
Michael Darnell
Michael Darnell - avatar