2016-11-24 16 views
0

我遇到下面的代碼有問題。我正在經歷不同的行爲,具體取決於我使用的IDE。將const char *傳遞給file.open(),奇怪的行爲

Dev-C++:運行良好。但是,如果我通過GenerateFileName(0,0)file.open(),則不會創建任何文件。

的Visual Studio 2013:奔跑在所有情況下都正常,但是,生成的文件名看起來像

ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌPùD 

或類似的東西,而文件本身沒有擴展名(我期待有一個.txt文件)。

int main() 
{ 
    ofstream file; 
    file.open(GenerateFileName(3, 0)); 
    file << 1 << endl; 
    file.close(); 
    _getch(); 
} 

const char* GenerateFileName(int Instance_nth, int Input_nth) 
{ 
    string filename = to_string(Instance_nth); 
    filename += "_"; 
    filename += to_string(Input_nth); 
    filename += ".txt"; 

    return filename.c_str(); 
} 
+3

在'GenerateFileName()'變量'filename'被銷燬該函數返回時,所以函數的返回值是垃圾。 – Leon

+2

您正在返回一個指向局部變量的指針。這是UB。 –

+2

只從函數返回字符串 – Borgleader

回答

4
const char* GenerateFileName(int Instance_nth, int Input_nth) 
{ 
    string filename = to_string(Instance_nth); 
    filename += "_"; 
    filename += to_string(Input_nth); 
    filename += ".txt"; 

    return filename.c_str(); 
} 

你返回一個指針由filename內部存儲的數據,同時它與GenerateFileName的結束破壞:返回值是一個懸掛指針,而你的代碼是未定義的行爲。

你可以做的是返回的std::string代替const char*一個:

std::string GenerateFileName(int Instance_nth, int Input_nth) 
{ 
    string filename = to_string(Instance_nth); 
    filename += "_"; 
    filename += to_string(Input_nth); 
    filename += ".txt"; 

    return filename; 
} 

用法將成爲:

file.open(GenerateFileName(3, 0).c_str()); 
+0

謝謝。但我仍然想知道爲什麼代碼在Dev C++上運行良好(除了將GenerateFileName(0,0)傳遞到file.open())但不在Visual Studio中的場景。 –

+3

未定義的行爲=你不能指望它運行良好,但你不能指望它肯定崩潰。你的代碼可以在一些版本的編譯器上運行良好 - 看起來就像你的Dev C++版本背後的編譯器一樣,但是你可能在不同的編譯器或者同一編譯器的不同版本中有不同的行爲 – wasthishelpful

1

這是不確定的行爲,因爲filename被破壞,一旦你離開GenenerateFileName功能,file.open正在接受指針,它指向已毀可變數據。

最簡單的事情在這裏是從GenerateFileName返回std::string,並完成類似file.open(GenerateFileName(0,0).c_str());

相關問題