2010-09-07 56 views
0

在我的程序中,我試圖構建一個文件名,其路徑指向存儲數據的特定文件夾。我看起來像這樣:無法在程序中指定文件路徑前綴

string directoryPrefix = "C:\Input data\"; 
string baseFileName = "somefile.bin"; 
string fileName = directoryPrefix + index + " " + baseFileName; 

但是,編譯器總是說我在第一行結尾處缺少一個分號。我如何正確設置它,以便它能工作?

感謝

回答

2

\是一個特殊字符

string directoryPrefix = "C:\Input data\"; 你有串\I\"等你的字符串沒有終止

翻倍的\逃離轉義字符的特殊命令

string directoryPrefix = "C:\\Input data\\";

+0

啊,謝謝。好吧,這很直觀...... – Faken 2010-09-07 17:00:53

2

您需要逃生charecters添加到每個「\」在一個字符串被接受。

string directoryPrefix = "C:\\Input data\\"; 

訪問this瞭解更多細節。

0

幾個答案已經提到加倍反斜槓。另一種可能性是使用正斜槓,而不是:

std::string directoryPrefix = "C:/Input data/"; 

即使Windows不接受正斜槓在命令行上,它會你在程序中使用他們接受他們。

1

如注意的\是一個特殊的轉義字符,當在字符串或字符文字中使用時。你有太多的選擇。要麼避免使用斜槓(所以雙斜槓),要麼移動到反斜槓,這也適用於所有其他操作系統,以便將來您的代碼更易於移植。

string directoryPrefix = "C:\\Input data\\"; 
string directoryPrefix = "C:/Input data/"; 

或者最好的選擇是移動到表示文件系統的平臺中性方式。

相關問題