views:

34

answers:

2

I am tearing my hair out over this error.

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

I have looked all around the interwebs but I can not find an answer. Here is the code that the error is happening in.

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); 
    }
   }
   }

Any ideas? It is a simple windows form application. I am using Visual Studio C++ 2010

Thanks

Colum

A: 

It's simply a conversion error:

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

Possible solution is posted here:

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

Opening Files

Convert System::String to const char*

Leniel Macaferi
I used ptrToStringChars() but now I get this conversion error:error C2664: 'fprintf' : cannot convert parameter 2 from 'cli::interior_ptr<Type>' to 'const char *' with [ Type=const wchar_t ] Cannot convert a managed type to an unmanaged type
Colum
Try http://stackoverflow.com/questions/56561/what-is-the-best-way-to-convert-between-char-and-systemstring-in-c-cli/56779#56779
Leniel Macaferi
A: 

If factoryname->Text identifies a property, then its getter may throw a CLR exception, in which case you will leak the file handle OutFile. Consider not using fopen, etc. It's a C library function and there are better alternatives such as std::ofstream.

Alternatively, as you have .NET available, you could use StreamWriter which will let you pass System::String and thus avoid your conversion problem as well:

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

C++/CLI will take care of closing the writer when the scope is exited.

Daniel Earwicker
It worked like a charm. Your a life saver
Colum