C++中的空字符常量
Empty character constant in C++
我从一个教程中复制了这段代码。然而,我一直收到一个错误,指出我不能有任何空的字符常量。该教程在Visual Studio 2008中,我使用的是Visual Studio 2013,所以这可能不再有效,但我找不到任何修复程序。
这是代码:
#include "stdafx.h"
#include <iostream>
class MyString
{
private:
char *m_pchString;
int m_nLength;
public:
MyString(const char *pchString="")
{
// Find the length of the string
// Plus one character for a terminator
m_nLength = strlen(pchString) + 1;
// Allocate a buffer equal to this length
m_pchString = new char[m_nLength];
// Copy the parameter into our internal buffer
strncpy(m_pchString, pchString, m_nLength);
// Make sure the string is terminated
// this is where the error occurs
m_pchString[m_nLength-1] = '';
}
~MyString() // Destructor
{
// We need to deallocate our buffer
delete[] m_pchString;
// Set m_pchString to null just in case
m_pchString = 0;
}
char* GetString() { return m_pchString; }
int GetLength() { return m_nLength; }
};
int main()
{
MyString cMyName("Alex");
std::cout << "My name is: " << cMyName.GetString() << std::endl;
return 0;
}
我得到的错误如下:
错误1错误C2137:空字符常量
此行:
m_pchString[m_nLength-1] = '';
你的意思可能是:
m_pchString[m_nLength-1] = ' ';
甚至:
m_pchString[m_nLength-1] = 0;
字符串以零结尾,写为纯0
或空字符' '
。对于双引号字符串""
,零终止字符隐式添加到末尾,但由于显式设置了单个字符,因此必须指定哪个字符。
你说过你"如果我使用null终止符,则得到一个错误,说明strncpy不安全,但您使用strlen
,如果字符串不是以null结尾,则就不起作用。来自cplusplus:
C字符串的长度由终止的空字符决定
我的建议是像其他人建议的那样使用null或0,然后每次复制整个字符串时只使用strcpy
而不是strncpy
。
您认为以null结尾的字符串怎么样?是的,你是对的,这样的字符串必须以null结尾:
m_pchString[m_nLength-1] = 0;
相关文章:
- 多字符常量警告
- const_cast<字符 *>(字符* 常量) 不是左值?
- 常量字符数组模板与字符常量* 函数重载
- 如何检查字符常量是否符合ASCII
- 从字符串数组转换为字符* 常量
- 字符常量或字符串常量
- 字符常量数组为空,即使已为其赋值 [C++]
- 如何创建 ' 字符常量
- 如何编写完全可移植的 4 字节字符常量的编译时初始化
- 我得到以下错误:[警告]多字符字符常量
- C++错误:警告:多字符字符常量/a用于用法
- 字符常量和函数名称的 sizeof() 背后的逻辑
- 如何在 C 中将多字符常量转换为整数
- C++ wifstream:不兼容的字符常量*,wchar_t康斯特*类型
- 不允许从"常量无符号字符*常量*"到"常量字符*常量*"static_cast
- 修改字符 *常量字符串
- 为什么字符常量/文字不能为空?
- C++字符 * 常量与字符 *,为什么有时一个有时另一个
- 警告多字符字符常量 [-Wmultichar]
- 开关语句多字符常量