【发布时间】:2015-07-02 19:50:34
【问题描述】:
我从教程中复制了这段代码来玩玩,但是我一直收到一个错误,指出我不能有任何空字符常量。该教程在 VS 2008 中,我使用的是 VS 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;
}
我得到的错误如下:
Error 1 error C2137: empty character constant
任何帮助将不胜感激
再次感谢。
【问题讨论】:
-
要终止 C 风格的字符串,请使用空字符 '\0'。
-
您知道吗:如果您双击“错误列表”选项卡中的 Visual Studio 错误,它会将您带到发生错误的行并突出显示错误?它使查找和解决此类问题变得更加容易。另外,发到 SO 时,请附上行号?
-
@kfsone 平心而论,Manny 确实知道是哪一行导致了问题,甚至在代码中用注释标记了它。
-
在cmets中说是哪里出错了,不过下次会在解释中放上来,谢谢。
标签: c++