【问题标题】:Trying to write a textfield value to file in c++尝试在 C++ 中将文本字段值写入文件
【发布时间】:2010-07-03 00:20:55
【问题描述】:

我为这个错误而抓狂。

 ------ Build started: Project: shotfactorybatchgen, Configuration: Debug Win32 ------
  shotfactorybatchgen.cpp
c:\documents and settings\administrator\my documents\visual studio 2010\projects\shotfactorybatchgen\shotfactorybatchgen\Form1.h(307): error C2664: 'fprintf' : cannot convert parameter 2 from 'System::String ^' to 'const char *'
          No user-defined-conversion operator available, or
          Cannot convert a managed type to an unmanaged type
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我浏览了整个互联网,但找不到答案。这是发生错误的代码。

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
   Decimal value;
   if(!Decimal::TryParse(textBox4->Text, value)) {
    MessageBox::Show("Non-numeric characters detected in 'Wait Time' filed", "Oops", MessageBoxButtons::OK, MessageBoxIcon::Warning);
   } else {
    if(!Decimal::TryParse(textBox3->Text, value)) {
     MessageBox::Show("Non-numeric characters detected in 'Max Upload' filed", "Oops", MessageBoxButtons::OK, MessageBoxIcon::Warning);
    } else {
     FILE *OutFile = fopen("run.bat","w");
     fprintf(OutFile,"@ECHO OFF\r\nC:\\Python26\\python.exe factory.py");
     if(factoryname->Text != ""){
      fprintf(OutFile," -f ");
      fprintf(OutFile,factoryname->Text);
     }
     fclose(OutFile); 
    }
   }
   }

有什么想法吗?它是一个简单的 Windows 窗体应用程序。我正在使用 Visual Studio C++ 2010

谢谢

【问题讨论】:

  • 您使用的语言称为 C++/CLI - 与标准 C++ 完全不同的野兽。将来在谷歌上搜索此类问题的答案时,使用正确的名称可能会有所帮助。我已相应地重新标记了您的问题。

标签: c++-cli


【解决方案1】:

如果factoryname->Text 标识了一个属性,那么它的getter 可能会抛出一个CLR 异常,在这种情况下你会泄露文件句柄OutFile。考虑不要使用fopen等。它是一个C库函数,有更好的替代品,例如std::ofstream

或者,由于您有 .NET 可用,您可以使用 StreamWriter,它可以让您通过 System::String,从而避免您的转换问题:

StreamWriter writer(someFilePath);
writer.WriteLine(someString);

C++/CLI 会在退出作用域时关闭writer

【讨论】:

    【解决方案2】:

    这只是一个转换错误:

    cannot convert parameter 2 from 'System::String ^' to 'const char *'
    

    这里发布了可能的解决方案:

    What is the best way to convert between char* and System::String in C++/CLI

    Opening Files

    Convert System::String to const char*

    【讨论】:

    • 我使用了 ptrToStringChars() 但现在我得到了这个转换错误:错误 C2664: 'fprintf' : cannot convert parameter 2 from 'cli::interior_ptr' to 'const char *' with [ Type=const wchar_t ] 无法将托管类型转换为非托管类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多