c++使用 tolower 时 cstrings 出现格式错误
您好,所以我尝试采用 cstring 并将其设置为小写,但是当我在最后打印 cstring 时,我收到一个奇怪的格式框,其中一些字母应该在其中。有人有什么想法吗?
#include <string>
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
int i=0;
char* str="TEST";
char c;
char* cstr = new char[strlen(str) + 1];
while (str[i])
{
c = str[i];
c = tolower(c);
strcat(cstr, &c);
i++;
}
cout << cstr << endl;
return 0;
}
Hi so I am trying to take a cstring and make it lowercase, but when I am printing the cstring at the end I am getting a weird format box where some of the letters should be. Do anyone have any ideas?
#include <string>
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
int i=0;
char* str="TEST";
char c;
char* cstr = new char[strlen(str) + 1];
while (str[i])
{
c = str[i];
c = tolower(c);
strcat(cstr, &c);
i++;
}
cout << cstr << endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是您错误地调用了
strcat
。第二个参数不是以 null 结尾的字符串。您实际上根本不需要调用
strcat
。只需直接写入输出字符串:尝试:
或者等效的:
The problem is that you are calling
strcat
incorrectly. The second parameter is not a null-terminated string.You really don't need to call
strcat
at all. Just write directly to the output string:Try:
or, equivalently:
strcat
需要一个空终止char*
,因此通过给出本地char
的地址,您将调用 < a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">未定义行为。此外,
new char[std::strlen(str) + 1]
不会将数组初始化为0
,这意味着cstr
不会要么正确地以空值终止;将()
添加到new[]
会导致数组被值初始化。试试这个:
strcat
expects a null-terminatedchar*
, so by giving the address of a localchar
you are invoking undefined behavior.Additionally,
new char[std::strlen(str) + 1]
does not initialize the array to0
s, meaningcstr
won't be properly null-terminated either; adding()
to thenew[]
causes the array to be value-initialized.Try this instead:
strcat 的第二个参数应该是一个以 null 结尾的字符串,而不是单个字符的地址。 strcat 不适合这种用途。
The second argument of strcat is supposed to be a null terminated string, not the address of a single character. strcat isn't appropriate for this use.
或者更短:
...
Or even shorter:
...