user16117959
user16117959

Reputation:

How to store the text from a .txt file into a variable

I want to save the text from a .txt file as a char variable on C++. I have tried:

char fileData;
fstream myFile;
myFile.open("file name");
fileData = myFile;
myFile.close();
cout<<fileData;

But it is wrong, I get an error invalid user-defined conversion from 'std::fstream {aka std::basic_fstream<char>}' to 'int' [-fpermissive]

Can anyone help me?

Upvotes: 1

Views: 944

Answers (1)

Mayank Gupta
Mayank Gupta

Reputation: 34

After opening a file, you also need to read it in order to obtain its data in a variable.

Also, I noticed that you didn't specify if you were reading a file, or writing to a file.

You can obtain the contents of the file in this manner:

myfile>>fileData;

You can specify whether the file is to be opened in read mode or write mode, by ios::in or ios::out respectively.

myfile.open ("demo.txt", ios::out| ios::in );

Upvotes: 0

Related Questions