C ++使用动态数组将小写字母更改为大写字母
C++ change lowercase to Uppercase using a dynamic array
我正在尝试使用动态数组将小写单词更改为大写单词。我 运行 进入了一个我以前没有遇到过的东西,叫做 "Heap Corruption"。有人可以向我解释我做错了什么并可能帮助解决这个问题吗?
#include <iostream>
#include <cctype>
#include <new>
#include <string>
using namespace std;
int main()
{
int i;
int w;
char *p;
string str;
cout << "Change lowercase to UPPERCASE!" << endl;
cout << "Enter Word: ";
cin >> str;
w = str.length();
p = new (nothrow) char[w];
if (p == nullptr)
cout << "Error: memory could not be allocated" << endl;
else
{
cout << "Re-Enter Word: ";
cin >> p[w];
for (i = 0; i < w; i++)
cout << static_cast<char>(toupper(p[i]));
cout << endl;
}
delete[] p;
cout << "Press <Enter> to Exit";
cin.get();
return 0;
}
无需使用 char*
转换为大写。相反,您可以像这里一样使用 std::transform:
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;
---编辑---
如果出于任何(学术)原因,您想在动态分配的 char
数组上执行大写转换,那么您仍然可以为此使用 std::transform
。
但是,正如您在下面的代码片段中看到的,您需要为表示字符串结束的尾随 [=15=]
-char 分配一个额外的字符。
char* szStr = new char[w+1];
std::transform(str.begin(), str.end(), szStr, ::toupper);
szStr[w]='[=11=]';
cout << szStr << endl;
你犯了很多错误,但只回答你的问题:
p = new (nothrow) char[w + 1];
这样我们就有空终止字符 ('\0') 的空间
同时使用:
cin >> p;
我正在尝试使用动态数组将小写单词更改为大写单词。我 运行 进入了一个我以前没有遇到过的东西,叫做 "Heap Corruption"。有人可以向我解释我做错了什么并可能帮助解决这个问题吗?
#include <iostream>
#include <cctype>
#include <new>
#include <string>
using namespace std;
int main()
{
int i;
int w;
char *p;
string str;
cout << "Change lowercase to UPPERCASE!" << endl;
cout << "Enter Word: ";
cin >> str;
w = str.length();
p = new (nothrow) char[w];
if (p == nullptr)
cout << "Error: memory could not be allocated" << endl;
else
{
cout << "Re-Enter Word: ";
cin >> p[w];
for (i = 0; i < w; i++)
cout << static_cast<char>(toupper(p[i]));
cout << endl;
}
delete[] p;
cout << "Press <Enter> to Exit";
cin.get();
return 0;
}
无需使用 char*
转换为大写。相反,您可以像这里一样使用 std::transform:
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;
---编辑---
如果出于任何(学术)原因,您想在动态分配的 char
数组上执行大写转换,那么您仍然可以为此使用 std::transform
。
但是,正如您在下面的代码片段中看到的,您需要为表示字符串结束的尾随 [=15=]
-char 分配一个额外的字符。
char* szStr = new char[w+1];
std::transform(str.begin(), str.end(), szStr, ::toupper);
szStr[w]='[=11=]';
cout << szStr << endl;
你犯了很多错误,但只回答你的问题:
p = new (nothrow) char[w + 1];
这样我们就有空终止字符 ('\0') 的空间
同时使用:
cin >> p;