C++ 逐行读取文件但行类型为 CString 或 TCHAR

标签 c++ file file-io cstring

我得到以下例子

    CString line[100];

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

那“行”怎么能存入类型为CString或TCHAR的值。我收到这样的错误:

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

请帮助我:)

最佳答案

首先声明:

CString line[100];

定义了一个包含 100 个 CString数组:你确定要那个吗?

或者您可能只希望一个 CString 将每一行读入?

// One line
CString line;

您可以选择将行读入 std::string,然后将结果转换为 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();
}

关于C++ 逐行读取文件但行类型为 CString 或 TCHAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910344/

相关文章:

c++ - 使用自动引用类在 C++ 中创建堆栈时出现问题

c++ - 位 c 操作

python - 在 Twisted 中发送大文件

java - 如何获取读取文件的进度

python - 写入多个流的包装器

c++ - map [] 操作数不起作用 C++

file - 读取 FITS 文件

java - 在 Java 中循环输出到 .txt 文件

c# - 每行的文本文件代表一个用户,我可以更新特定行吗?

C++将文本写入文件,如何多行