1

I was just wondering, is there anyway that you can have your user input the location of a file when trying to using a stream?

Ex of what I want to do:

int main()
{
ifstream instream; 

string file_location;
cout << "Enter in file location: " << endl; 
cin >> file_location;
instream.open(file_location);
}

So I want them to input the file location but the program won't compile.

The error message I'm getting is:

no matching function for call to 'std::basic_ifstream >::open(std::string&)'

Xyz
  • 5,955
  • 5
  • 40
  • 58
knguyen2525
  • 95
  • 1
  • 8

2 Answers2

1

Use instream.open(file_location.c_str()); instead.

kol
  • 27,881
  • 12
  • 83
  • 120
0

You have the right idea, but your types are a little incorrect. open takes a const char*, not a std::string, so you need to provide the const char* that the string contains. The c_str() method of std::string will return the const char* that represents the std::string.

For instance:

instream.open(file_location.c_str());
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
  • After turning it into a cstring, I still get the error: request for member 'c_str' in 'file_location', which is of non-class type 'char' – knguyen2525 Nov 14 '11 at 03:42
  • 1
    @kol: So it was, and yours was posted while I was still typing, so I upvoted you. – Scott Stafford Nov 14 '11 at 03:50
  • @knguyen2525: Something doesn't quite add up.. Are you doing an array index you didn't mention? See this SO post: http://stackoverflow.com/questions/1694798/c-error-converting-a-string-to-a-double – Scott Stafford Nov 14 '11 at 03:51
  • I got it to work. I'm supposed to keep it a type string and convert it into a cstring. Thanks for all the help guys! – knguyen2525 Nov 14 '11 at 04:52