2010-07-03 58 views
1

我正在撕掉我的頭髮在這個錯誤。試圖寫一個文本字段值在C++中的文件

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

我看過周圍所有的interwebs,但我找不到答案。這裏是錯誤發生的代碼。

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

感謝

科拉姆

+1

您使用的語言稱爲C++/CLI - 與標準C++非常不同。如果使用正確的名稱來搜索類似問題的答案,它可能會有所幫助。我已經相應地重新標記了你的問題。 – 2010-07-03 00:31:07

回答

1

如果factoryname->Text標識屬性,則其吸氣劑可拋出一個CLR例外,在這種情況下,你會泄漏文件句柄OutFile。考慮不使用fopen等。它是一個C庫函數,並且有更好的替代方法,如std::ofstream

或者,正如你所.NET中可用,您可以使用StreamWriter這將讓你通過System::String,從而避免您的轉換問題,以及:

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

C++/CLI將採取關閉writer時的護理範圍退出。

+0

它像一個魅力一樣工作。你的救星 – Colum 2010-07-03 02:13:05

0

這是一個簡單的轉換錯誤:

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*

+0

我用ptrToStringChars(),但現在我得到這個轉換錯誤: 錯誤C2664:'fprintf中:不能從轉換參數2 'CLI :: interior_ptr ' 到 '爲const char *' 與 [ 類型=常量爲wchar_t ] 無法將託管類型轉換爲非託管類型 – Colum 2010-07-03 01:08:04

+0

嘗試http://stackoverflow.com/questions/56561/what-is-the-best-way-to-convert-between-char-and-systemstring-in-c -cli/56779#56779 – 2010-07-03 01:27:17