代码之家  ›  专栏  ›  技术社区  ›  Colum

尝试在C++中向文件中写入TeXField值

  •  1
  • Colum  · 技术社区  · 16 年前

    我正在为这个错误大伤脑筋。

     ------ 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

    谢谢

    科勒姆

    2 回复  |  直到 16 年前
        1
  •  1
  •   Daniel Earwicker    16 年前

    如果 factoryname->Text 标识属性,则其getter可能引发CLR异常,在这种情况下,将泄漏文件句柄 OutFile . 考虑不使用 fopen 等等。它是一个C库函数,有更好的选择,比如 std::ofstream .

    或者,由于.NET可用,您可以使用 StreamWriter 哪个让你过去 System::String 从而避免转换问题:

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

    C++/CLI将负责关闭 writer 当作用域退出时。

        2
  •  0
  •   Community Mohan Dere    9 年前

    这只是一个转换错误:

    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*

    推荐文章