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)
"并且'在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)
| 归档时间: |
|
| 查看次数: |
2402 次 |
| 最近记录: |