-6
  • I have written a patch to write to a file and its working
//To write a file from this location 
std::ofstream myfile; 
myfile.open("warn_sen.txt"); 
myfile << "IT HITS HERE = " "\n"; 
myfile.close();
  • But read operation is failing, stating that the conversion is not supported.
//To read a file from this location 
std::ifstream evadefile;
evadefile.open("evade_sen.txt");
string flag_01 =  evadefile;
evadefile.close();

ERROR - E0312 no suitable user-defined conversion from "std::ifstream" to "std::string" exists

Please assist me with the same, thank you so much.

  • 5
    What made you believe that `string flag_01 = evadefile;` is how you read contents of a file? What documentation did you consult? – UnholySheep Jul 08 '22 at 12:58
  • Use proper code to read from file according to what you want to read. Some of the options are [`operator>>`](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) and [`std::getline()`](https://en.cppreference.com/w/cpp/string/basic_string/getline). – MikeCAT Jul 08 '22 at 12:59
  • Alternatively, if you want to read the entire file contents, this might give you a good starting point: https://blog.insane.engineer/post/cpp_read_file_into_string/ (DISCLAIMER: I'm the author) – Joel Bodenmann Jul 08 '22 at 13:00
  • 1
    Also we already told you what's the problem [last time you asked](https://stackoverflow.com/questions/2649735/how-to-link-static-library-into-dynamic-library-in-gcc) – πάντα ῥεῖ Jul 08 '22 at 13:29
  • @πάνταῥεῖ did you intend [this link](https://stackoverflow.com/questions/72900707/i-am-trying-to-do-a-basic-file-operation-in-c)? This question has been posted before and closed before, with several comments explaining the problem. – Drew Dormann Jul 08 '22 at 13:42
  • @drew yes, wrong copy. – πάντα ῥεῖ Jul 08 '22 at 13:44

1 Answers1

2

If you want to read the whole file into string, you can do the following.

std::ifstream evadefile;
evadefile.open("evade_sen.txt");
string flag_01(std::istreambuf_iterator<char>{evadefile}, {}); // in header <iterator>
evadefile.close(); // By the way, you can also omit this line if you are going to work only with this file using the ifstream, because of RAII
Karen Baghdasaryan
  • 2,407
  • 6
  • 24