C++连接字符串问题

Mar*_*lor 1 c++ string concatenation

为什么以下代码不起作用?

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

它应该在输入任何文件名的末尾连接".txt"

此外,当我尝试编译它(使用g ++)时,这是错误消息

替代文字

In *_*ico 15

使用双引号而不是单引号.

strcat(filename, ".txt"); 
Run Code Online (Sandbox Code Playgroud)

在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"
Run Code Online (Sandbox Code Playgroud)

普通的字符串文字通常是ASCII,而宽字符串文字通常是某种形式的Unicode编码(尽管C++语言并不能保证这一点 - 请检查编译器文档).

编译器警告提及,int因为C++标准(2.13.2/1)表示包含多个字符文字的字符文字char实际上具有类型int,该类型具有实现定义的值.

如果您正在使用C++,那么最好使用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; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 规则1:在高警告级别下干净地编译(http://www.gotw.ca/publications/c++cs.htm).接得好; 制作(和错过)是一个简单的错误. (2认同)

Mar*_*k B 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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Mark:这很有趣,但请注意结果和做法不应该被记住; 你会得到坏习惯和虚假信息.如果你真的想*学习它,你必须得到一本书. (4认同)
  • 如果您正在阅读的材料建议使用字符数组和`strcat`而不是使用`std :: string`,那么您可能正在阅读C教程或编写得很糟糕的C++教程. (2认同)