Question

I get the following example

    CString line[100];

    //string line;
    ifstream myfile (_T("example.txt"));
    if (myfile.is_open())
    {
       while ( getline (myfile,line) )
       {
          cout << line << '\n';
       }
       myfile.close();
     }

How does that "line" can stored values ​​to type CString or TCHAR. I get an error like this:

error C2664: '__thiscall std::basic_ifstream >::std::basic_ifstream >(const char *,int)'

Please help me :)

Was it helpful?

Solution

First, this statement:

CString line[100];

defines an array of 100 CStrings: are you sure you want that?

Or maybe you just want one CString to read each line into?

// One line
CString line;

An option you have is to read the lines into a std::string, and then convert the result to CString:

string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
   while (getline(myfile, line))
   {
      // Convert from std::string to CString.
      //
      // Note that there is no CString constructor overload that takes
      // a std::string directly; however, there are CString constructor
      // overloads that take raw C-string pointers (e.g. const char*).
      // So, it's possible to do the conversion requesting a raw const char*
      // C-style string pointer from std::string, calling its c_str() method.
      // 
      CString str(line.c_str());

      cout << str.GetString() << '\n';
   }
   myfile.close();
}

OTHER TIPS

The 2nd parameter of std::getline() requires a std::string, so use the std::string first, then convert it to a CString

string str_line;
ifstream myfile (_T("example.txt"));
if (myfile.is_open())
{
   while ( getline (myfile, str_line) )
   {
      CString line(str_line.c_str());
      cout << line << '\n';
   }
   myfile.close();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top