reading in data provided a filename(C++)

  • Ponzzz
  • Born
  • Born
  • Ponzzz
  • Posts: 3

Post 3+ Months Ago

I am trying to implement a function called addFile(string file). This does exactly as it sounds, it will take data from a second file and read it in. Where I run into problems is how to go about storing the filename so the below code works.

Code: [ Select ]
ifstream myfile (file);


this will generate an error since the argument doesn't take a string(from what I know it's a const char* <name>). I HAVE to provide the file name and store it into a variable so it isn't as easy as just supplying the filename directly into the code. I cant quite figure out how to supply the argument with the appropriate variable type and also implement it like the below code. Maybe im just overthinking this lol

Code: [ Select ]
cout << "What is the name of the file you would like to add?" << endl;
        cin >> input;

        addFile(input);
  1. cout << "What is the name of the file you would like to add?" << endl;
  2.         cin >> input;
  3.         addFile(input);


any tips or suggestions?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6251
  • Loc: Seattle, WA

Post 3+ Months Ago

Store the filename in a std::string, then pass the underlying c_string to the function:

CPP Code: [ Select ]
string input;
cout << "What is the name of the file you would like to add?"
     << endl;
cin >> input;
if( input != "" ) {
    addFile(input.c_str());
}
  1. string input;
  2. cout << "What is the name of the file you would like to add?"
  3.      << endl;
  4. cin >> input;
  5. if( input != "" ) {
  6.     addFile(input.c_str());
  7. }

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 97 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.