سؤال

هذا السؤال لديه بالفعل إجابة هنا:

أنا أتعلم C ++ وأنا أحصل على بعض المشاكل عندما أحاول استخدام سلسلة في ifstream الطريقة، مثل هذا:

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );

هنا هو الكود الكامل:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
    string file;
    long begin,end;
    cout << "Enter the name of the file: ";
       cin >> file;
    ifstream myfile ( file );
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    cout << "File size is: " << (end-begin) << " Bytes.\n";

    return 0;
}

وهنا خطأ الكسوف، عاشر قبل الطريقة:

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'

ولكن عندما أحاول ترجمة في الكسوف، فإنه وضع عاشر قبل الطريقة، يشير إلى وجود خطأ في بناء الجملة، ولكن الخطأ في بناء الجملة؟ شكرا!

هل كانت مفيدة؟

المحلول

يجب أن تمر char* ل ifstream منشئ، واستخدام c_str() وظيفة.

// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() 
{   
  string filename;
  cout << "Enter the name of the file: ";
  cin >> filename;
  ifstream file ( filename.c_str() );    // c_str !!!
}

نصائح أخرى

المشكلة هي أن منشئ Ifstream لا يقبل سلسلة، ولكن سلسلة نمط C:

explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );

و std::string لا يوجد لديه تحويل ضمني إلى سلسلة نمط C، ولكن صريح واحد: c_str().

يستخدم:

...
ifstream myfile ( file.c_str() );
...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top