2010-08-24 106 views
1

爲什麼下面的代碼不起作用?C++連接字符串問題

#include <iostream> 
#include <string> 
int main(){ 
    char filename[20]; 
    cout << "Type in the filename: "; 
    cin >> filename; 
    strcat(filename, '.txt'); 
    cout << filename; 
} 

應該串聯「.TXT」上任意的文件名被輸入

另外結束時,當我試圖編譯它(與克++)這是錯誤消息

alt text

+4

很多人都在說使用'的std :: strings'代替字符數組。除了'std :: strings'由於支持諸如串接之類的東西而更易於使用,它們也更安全使用,因爲使用字符數組時容易引入(可利用的)錯誤。例如,如果用戶輸入的文件名長於19(1個字符用於空終止符)字符會怎麼樣? – Brian 2010-08-24 18:28:15

回答

15

使用雙引號而不是單引號。

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; 
} 
+0

哇...這麼簡單... – 2010-08-24 18:18:18

+2

規則1:在高警告級別編譯乾淨(http://www.gotw.ca/publications/c++cs.htm)。接得好;這是一個容易犯的錯誤(和錯過)。 – gregg 2010-08-24 18:22:58

+1

還要注意,字符串以'\ 0'結尾,因此比它們看起來長1個字符。 – 2010-08-24 18:37:23

7

"'用C意味着不同的事情++。單引號表示一個字符,而雙引號表示一個C字符串。你應該使用".txt"

鑑於這是C++但是,不要使用C風格char[]可言:使用std::string代替:

#include <iostream> 
#include <string> 
int main(){ 
    std::string filename; 
    cout << "Type in the filename: "; 
    cin >> filename; 
    filename += ".txt"; 
    cout << filename; 
} 
+0

啊,我已經習慣了PHP ...幾天前開始使用C++ – 2010-08-24 18:19:03

+0

@Mark:忘記了解任何語言。你需要獲得[一本書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)並從頭開始。 – GManNickG 2010-08-24 18:33:14

+2

如果您正在閱讀的資料是使用字符數組和'std :: string'使用'strcat',那麼您可能正在閱讀C教程或編寫不好的C++教程。 – Brian 2010-08-24 18:33:41

2

strcat的第二個參數使用字符串(雙引號)。您正在使用單引號(==整數)

艾哈邁德