Empty Character Constant in C++
I Copied This Code from a Tutorial to Play Around With, However I Kept on Getting an Error That Stated That I Can't Have Any Empty Character Constants. the...
I copied this code from a tutorial to play around with, however I kept on getting an error that stated that I can't have any empty character constants. the tutorial was in VS 2008, and I am using VS 2013, so perhaps this is no longer valid, but I can't find any fix. here is the code:
#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;
}
The error I get is the following:
Error 1 error C2137: empty character constant
Any help will be greatly appreciated
Thanks again.
3 Answers
This line:
m_pchString[m_nLength-1] = '';
What you probably mean is:
m_pchString[m_nLength-1] = '\0';
Or even:
m_pchString[m_nLength-1] = 0;
Strings are zero terminated, which is written as a plain 0 or the null character '\0'. For double quote strings "" the zero termintation character is implicitly added to the end, but since you explicitly set a single character you must specify which.
what do you think about null-terminated string? Yes, you are right, such strings must be terminated with null:
m_pchString[m_nLength-1] = 0;
You've said that you "get an error stating that strncpy is unsafe to use if i use the null terminator," but you use strlen, which simply does not work if the string isn't null terminated. From cplusplus:
The length of a C string is determined by the terminating null-character
My suggestion to you would be to use null or 0 like others are suggesting and then just use strcpy instead of strncpy as you copy the whole string every time anyways.