open file with different names

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • siato
    New Member
    • Mar 2008
    • 1

    open file with different names

    I want to open a file in my code ( Visual C++ 2005) in the way that the file name contains some variables.
    while i using f.open("file_na me.ext") ; i prefer to put a string instead of fix name

    Code:
    string s;
    s="name1.ext";
    ofstream f;
    f.open(s);
    i receive an error
    error C2664: 'void std::basic_ofst ream<_Elem,_Tra its>::open(cons t wchar_t *,std::ios_base ::openmode,int) ' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *'
    with
    [
    _Elem=char,
    _Traits=std::ch ar_traits<char>
    ]
    No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called



    help me out plz
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    It’s because, rather surprisingly, the fstream open member function requires a char* string (i.e. C string), and is not designed to handle C++ strings as well. But it’s no problem if you use a C++ string. Fortunately, the C++ string class has a member function called c_str() that returns a temporary C string. So instead of
    Code:
    f.open(s)
    you want
    Code:
    f.open(s.c_str())
    .

    Comment

    Working...