【问题标题】:(C++ / CLI) Set contents of textbox to content of a .txt(C++ / CLI) 将文本框的内容设置为 .txt 的内容
【发布时间】:2016-08-25 12:35:17
【问题描述】:

我希望将文本框的内容设置为 .txt 文件的内容, 但是我无法让它工作。我有一个按钮可以“刷新” 文本框的内容到 .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++ 代码怎么样。 “字符串^”不是有效的 C++。它是标准 C++ 语言的仅限 Microsoft 的变种。
  • 这既不是 C++ 也不是调用 Windows API。如果您使用 C++/CLI,请使用适当的标记。如果这是针对 .NET,请使用适当的标记。请务必删除那些不是的。 (令人惊讶的是,如今的开发人员甚至不知道他们正在使用的编程语言或目标平台。Does Visual Studio Rot the Mind? 看起来确实如此。)
  • 好吧,每当我使用“String”而不是“String^”时,它都会给我一个错误提示“类 System::String 不存在默认构造函数”
  • 所以?从什么时候开始String(又名System::String)和std::string是一样的?买几本书,在你了解编程之前不要使用 IDE。
  • @NopeNope 它会给你带来好处,让你弄清楚你正在使用什么语言。提示:这不是 C++

标签: c++-cli iostream fstream


【解决方案1】:

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

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

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

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

【讨论】:

  • 我假设你有一个 using System::IO 命名空间声明。没有它,您需要完全限定名称。根据最新更新。
  • 感谢您的帮助!
【解决方案2】:

你忘了结束方法 c_str,把它改成 c_str()

【讨论】:

  • 对了,有什么办法可以做我所要求的吗?
  • @NopeNope 那么编译后,你的代码不行了?你调试了吗?
  • @DavidHeffernan line 可能是std::string,而不是System::String,检查编译错误。
  • 还不错,错过了
  • @DavidHeffernan "line" 是 std::string,因为这是 "getline()" 唯一能接受的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
相关资源
最近更新 更多