(C++ / CLI) 将文本框的内容设置为 .txt 的内容

(C++ / CLI) Set contents of textbox to content of a .txt

我希望将文本框的内容设置为 .txt 文件的内容, 但是我无法让它工作。我有一个按钮可以 "refresh" 文本框的内容到 .txt 文件的内容,这里是我使用的代码:

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    std::ifstream dat1("DataStore.txt");
    String^ textHolder;
    if (dat1.is_open())
    {
        while ( getline(dat1, line) )
        {
            textHolder += line.c_str;
        }
        textBox1->Text = textHolder;
        dat1.close();
    }
    else textBox1->Text = "Unable to open file";
}

我在编译程序时遇到了这两个错误:

error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str' to create a pointer to member

error C2297: '+=' : illegal, right operand has type 'const char *(__thiscall std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) throw() const'

如何进行这项工作?

注意:我试图在文本框中显示整个 .txt 文件的内容

您忘记结束方法 c_str,将其更改为 c_str()

如果您打算使用 C++/CLI,您不妨利用 .net。您可以使用 File class 为您阅读文件:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
{
    textBox1->Text = System::IO::File::ReadAllText("DataStore.txt");
}

您需要希望进程工作目录包含该文件。在 GUI 应用程序中,您最好指定文件的完整路径,因为工作目录通常定义不明确。

如果您正在尝试学习 C++,那么 .net C++/CLI WinForms 应用程序可能不是开始的地方。