【发布时间】:2013-03-10 07:13:51
【问题描述】:
我有一个私有类变量char name[10],我想在其中添加.txt 扩展名,以便我可以打开目录中存在的文件。
我该怎么做?
最好创建一个新的字符串变量来保存连接的字符串。
【问题讨论】:
标签: c++
我有一个私有类变量char name[10],我想在其中添加.txt 扩展名,以便我可以打开目录中存在的文件。
我该怎么做?
最好创建一个新的字符串变量来保存连接的字符串。
【问题讨论】:
标签: c++
首先,不要使用char* 或char[N]。使用std::string,其他一切都变得如此简单!
例子,
std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!
很简单,不是吗?
现在如果你出于某种原因需要char const *,比如当你想传递给某个函数时,那么你可以这样做:
some_c_api(s.c_str(), s.size());
假设这个函数被声明为:
some_c_api(char const *input, size_t length);
从这里开始探索std::string自己:
希望对您有所帮助。
【讨论】:
既然是 C++,为什么不使用 std::string 而不是 char*?
连接将是微不足道的:
std::string str = "abc";
str += "another";
【讨论】:
operator+= 执行释放和分配。堆分配是我们通常做的最昂贵的操作之一。
如果您使用 C 进行编程,那么假设 name 确实像您所说的那样是一个固定长度的数组,您必须执行以下操作:
char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...
你现在明白为什么每个人都推荐std::string了吗?
【讨论】:
移植的 C 库中有一个 strcat() 函数将为您执行“C 样式字符串”连接。
顺便说一句,尽管 C++ 有很多函数可以处理 C 风格的字符串,但如果你尝试想出你自己的函数来做这件事,它可能会有所帮助,比如:
char * con(const char * first, const char * second) {
int l1 = 0, l2 = 0;
const char * f = first, * l = second;
// step 1 - find lengths (you can also use strlen)
while (*f++) ++l1;
while (*l++) ++l2;
char *result = new char[l1 + l2];
// then concatenate
for (int i = 0; i < l1; i++) result[i] = first[i];
for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];
// finally, "cap" result with terminating null char
result[l1+l2] = '\0';
return result;
}
...然后...
char s1[] = "file_name";
char *c = con(s1, ".txt");
...其结果是file_name.txt。
您可能还想编写自己的operator +,但是不允许使用仅指针作为参数的 IIRC 运算符重载。
另外,不要忘记这种情况下的结果是动态分配的,因此您可能希望对其调用 delete 以避免内存泄漏,或者您可以修改函数以使用堆栈分配的字符数组,当然前提是它具有足够的长度。
【讨论】:
strncat()函数通常是更好的选择
strncat 在这里无关紧要,因为我们已经知道第二个参数".txt" 的长度。所以它只是strncat(name, ".txt", 4),这对我们没有任何好处。
C++14
std::string great = "Hello"s + " World"; // concatenation easy!
回答问题:
auto fname = ""s + name + ".txt";
【讨论】:
using namespace std::string_literals;
strcat(destination,source) 在c++中可以用来连接两个字符串。
要深入了解可以在以下链接中查找-
【讨论】:
最好使用 C++ 字符串类而不是老式的 C 字符串,生活会轻松很多。
如果你有旧式字符串,你可以转换成字符串类
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
string trueString = string (greeting);
cout << trueString + "and there \n"; // compiles fine
cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too
【讨论】:
//String appending
#include <iostream>
using namespace std;
void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}
while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}
int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);
stringconcat(str1, str2);
cout<<str1;
getchar();
return 0;
}
【讨论】: