-2

I've been working on a file reader that reads the data from inside the file and stores it in a string. My code compiles how it should when I hard-code the file name to be opened, but when I try to read in the file from the keyboard I get the error "no known conversion for argument 1 from str to const and I don't know why. Heres my code:

#include <iostream>
#include <fstream>
#include <string>

int main() {

 string fileName;
 cout << "Enter the file name to be read: ";
 cin >> fileName;
 ifstream input_file(fileName);
 std::string line_; // string which text file contents will be stored in

 if(input_file.is_open()){ // validation to see if the file is open
   while(getline(input_file, line_)){
     std::cout<<line_<< '\n'; //prints the contents of the file into the console
   }
  input_file.close();
 }
 else {
   std::cout<<"File is not open"<< '\n';
 }
 std::cin.get();
}
LC12382
  • 97
  • 2
  • 10

2 Answers2

1
#include <iostream>
#include <fstream>
#include <string>


int main() {

 std::string fileName;
 std::cout << "Enter the file name to be read: ";
 std::cin >> fileName;
 std::ifstream input_file(fileName.c_str());
 std::string line_; // string which text file contents will be stored in

 if(input_file.is_open()){ // validation to see if the file is open
   while(getline(input_file, line_)){
     std::cout<<line_<< '\n'; //prints the contents of the file into the console
   }
  input_file.close();
 }
 else {
   std::cout<<"File is not open"<< '\n';
 }
 std::cin.get();
}

Good luck...

Vassilis
  • 2,878
  • 1
  • 28
  • 43
  • 1
    Could use a bit of explaining of what you changed and why and correction of the missing `std::`s for completeness. – user4581301 Dec 13 '15 at 23:22
  • just added `using namespace std` cos I noticed that std::.. is not used with some `cout`, `cin`, etc. I also used a cstring in `filename` variable as you also said. `filename_c_str()` – Vassilis Dec 13 '15 at 23:26
  • Adding `using namespace std;` is not a very good solution. Read more: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – user4581301 Dec 13 '15 at 23:28
  • I think you mean it should be like this (edited). Thanks for the link. – Vassilis Dec 13 '15 at 23:31
0

Likely old compiler that can't take string as an argument. Use a cstring:

ifstream input_file(fileName.c_str());

Or specify -std=c++11 on the commandline to get C++11 support.

user4581301
  • 33,082
  • 7
  • 33
  • 54