使用雙引號而不是單引號。
strcat(filename, ".txt");
在C++中,單引號表示單個字符,雙引號表示字符的序列(字符串)。追加前的文字的L
表明它使用寬字符集:
".txt" // <--- ordinary string literal, type "array of const chars"
L".txt" // <--- wide string literal, type "array of const wchar_ts"
'a' // <--- single ordinary character, type "char"
L'a' // <--- single wide character, type "wchar_t"
普通字符串文字通常是ASCII,而寬字符串文字通常是某種形式的Unicode編碼的(雖然C++語言不保證這一點 - 檢查你的編譯器文檔)。
編譯器警告提到int
因爲C++標準(2.13.2/1)表示,其包含多個char
實際上具有字符文字輸入int
,其具有實現定義的值。
如果您使用C++不過,你最好不要使用std::string
代替,如Mark B曾建議:
#include <iostream>
#include <string>
int main(){
std::string filename;
std::cout << "Type in the filename: ";
std::cin >> filename;
filename += ".txt";
std::cout << filename;
}
很多人都在說使用'的std :: strings'代替字符數組。除了'std :: strings'由於支持諸如串接之類的東西而更易於使用,它們也更安全使用,因爲使用字符數組時容易引入(可利用的)錯誤。例如,如果用戶輸入的文件名長於19(1個字符用於空終止符)字符會怎麼樣? – Brian 2010-08-24 18:28:15