我最后的功能不起作用。该函数将一个文字字符串附加到C字符串中。它检查C字符串中是否有足够的空间将字符串附加到它。如果没有足够的空间,则C字符串长度必须扩展为(字符串长度+ C字符串长度)大小的两倍。然后它可以将字符串附加到C字符串。在运行程序并输入一个文本字符串后,显示第一个输出语句,然后在我收到“抛出std :: bad_alloc实例后调用terminate”的错误并且程序停止工作后。所有其他功能在此追加功能之前工作。有没有办法修复最后一个附加函数的工作?如何解决将字符串附加到C字符串的错误?
int main()
{
char* s1 = assign();
char* s2 = assign(" C++ ");
char* s3 = add(s1, s2);
cout << "length of \"" << s3 << "\" is " << strlen(s3) << endl;
append(s3, "programming language"); // This function doesn't work
cout << "length of \"" << s3 << "\" is " << strlen(s3) << endl;
return 0;
}
char* assign()
{
const int SIZE = 100;
char temp[SIZE];
int length;
int twicelen;
cout << "Enter a text string which will be used to append literal strings to it: ";
cin.getline(temp, SIZE);
length = strlen(temp);
twicelen = length * 2;
char* newCstring = new char[twicelen];
strcpy(newCstring, temp);
return newCstring;
}
char* assign(string str)
{
int len = strlen(str.c_str());
int newlen = len * 2;
char* newStr = new char[newlen];
strcpy(newStr, str.c_str());;
return newStr;
}
char* add(char* s1, char* s2)
{
strcat(s1, s2);
return s1;
}
void append(char* s3, string literalStr) // Every function before this works and this is where the program gives an error and closes.
{
if (sizeof(s3) < (strlen(s3) + strlen(literalStr.c_str()) + 1))
{
int expandLength = (strlen(s3) + strlen(literalStr.c_str())) * 2;
char* s3 = new char[expandLength];
strcat(s3, literalStr.c_str());
}
else
strcat(s3, literalStr.c_str());
}
为什么不使用std :: string? –
你在学习指针吗?否则,你应该使用'std :: string'。 –
添加一些输出以显示'sizeof(s3)'的值。这不是你想象的那样。 –