【问题标题】:Empty character constant in c++C ++中的空字符常量
【发布时间】: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++


【解决方案1】:

这一行:

m_pchString[m_nLength-1] = '';

你的意思可能是:

m_pchString[m_nLength-1] = '\0';

甚至:

m_pchString[m_nLength-1] = 0;

字符串以零结尾,写成普通的0 或空字符'\0'。对于双引号字符串"",零终止字符会隐式添加到末尾,但由于您显式设置了单个字符,因此您必须指定哪个字符。

【讨论】:

  • 也可以写"",因为字符串字面量是空终止的
  • 但随后我收到一条错误消息,指出如果我使用空终止符,则 strncpy 使用不安全
  • @ssnobody 这取决于,你不能写,说:m_pchString[m_nLength-1] = ""; 因为"" 实际上是一个指向空终止字符串的指针,而不是单个字符。
  • @Manny 更安全的版本是strncpy_s en.cppreference.com/w/c/string/byte/strncpy
  • @TommyA 是的。如果您想利用字符串文字终止,您可以使用 m_pchString[m_nLength-1] = ""[0]; 但这显然比 char 样式复杂得多(并且可读性较差)。
【解决方案2】:

您如何看待以空字符结尾的字符串?是的,你是对的,这样的字符串必须以null结尾:

m_pchString[m_nLength-1] = 0;

【讨论】:

  • 但是编译器说 strncpy 使用不安全
【解决方案3】:

你说过你“收到一个错误,指出如果我使用空终止符,strncpy 使用不安全,”但你使用strlen,这只是不起作用 如果字符串不是以 null 结尾的。来自cplusplus

C 字符串的长度由终止的空字符决定

我对您的建议是像其他人建议的那样使用 null 或 0,然后只需使用 strcpy 而不是 strncpy,因为您每次都复制整个字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2012-09-19
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多