CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2009
    Posts
    6

    Problem with setting filename using a string...

    I want to use the string - filename , as the file name, but I can't get it to work...
    How can I do this???


    I would also want to add Input to the file, where it says File Info, how would I do this...


    #include <cstdio>
    #include <iostream>
    #include <stdlib.h>
    #include <string>

    using namespace std;

    int main()
    {
    {
    string filename;
    cin >> filename;
    cout << filename;
    }
    FILE * file = fopen("This is where I want my string name" , ".dat","w");
    fprintf(file, "File Info");
    fclose(file);
    system ("PAUSE");
    return 0;
    }

    Any info. would be helpful...

  2. #2
    Join Date
    Aug 2007
    Posts
    858

    Re: Problem with setting filename using a string...

    Use string's c_str() method.

    Code:
    fopen(filename.c_str( ), "w");

  3. #3
    Join Date
    May 2009
    Posts
    6

    Re: Problem with setting filename using a string...

    I get the error message: 'filename' undeclared [first use of this function]...

  4. #4
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Problem with setting filename using a string...

    Quote Originally Posted by Adobe Dharuma View Post
    I get the error message: 'filename' undeclared [first use of this function]...
    Code:
    int main()
    {
        {
            string filename;
            cin >> filename;
            cout << filename;
        }
        FILE * file = fopen("This is where I want my string name" , ".dat","w");
        fprintf(file, "File Info");
        fclose(file);
        system ("PAUSE");
        return 0;
    }
    You're limiting its scope by using those braces. I don't see what purpose they serve here.

  5. #5
    Join Date
    Dec 2008
    Posts
    56

    Re: Problem with setting filename using a string...

    I also don't see the purpose of using fopen() when C++ provides the fstream (or more specifically, ofstream) class.

    Code:
    #include <fstream>
    
    int main()
    {
      ...
      std::cout << "Enter filename: ";
      std::cin   >> filename;
    
      std::ofstream ofs(filename.c_str());
    
      ofs << "File Info";
      ...
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured