Ошибка empty character constant

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 Visual Studio 2008, and I am using Visual Studio 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

Peter Mortensen's user avatar

asked Jul 2, 2015 at 19:50

BeepBoop's user avatar

5

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.

answered Jul 2, 2015 at 19:52

Tommy Andersen's user avatar

Tommy AndersenTommy Andersen

7,1651 gold badge31 silver badges50 bronze badges

9

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 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 anyway.

Peter Mortensen's user avatar

answered Jul 2, 2015 at 20:26

scohe001's user avatar

scohe001scohe001

15.1k2 gold badges31 silver badges51 bronze badges

0

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;

Peter Mortensen's user avatar

answered Jul 2, 2015 at 19:52

AnatolyS's user avatar

AnatolySAnatolyS

4,26918 silver badges28 bronze badges

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include<iostream.h>
#include<iomanip.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
 
void allocMemory(int m, int n, double **&Q);
void fillRandomMatrix(int m, int n, double **Q);
void findMax(int m, int n, int &mi, int &mj, double **Q);
void findMin(int m, int n, int &mi, int &mj, double **Q);
void outputMatrix(int m, int n, double **Q);
void freeMemory(int m, int n, double **Q);
 
int main()
{
    srand(time(NULL));
 
    int m, n, i, j;
    double **Q;
    Q=0;
 
    cout<<"n= ";
    cin>>n;
    cout<<endl;
    cout<<"m= ";
    cin>>m;
    cout<<endl;
    allocMemory(m, n, Q);
    fillRandomMatrix(m, n, Q);
    
    findMax(m, n, i, j, Q);
 
    cout<<"Maximal elements: ";
    cout<<endl;
    cout<<Q[i][j];
    cout<<endl;
 
    findMin(m, n, i, j, Q);
 
    cout<<"Minimal elements: ";
    cout<<endl;
    cout<<Q[i][j];
    cout<<endl;
 
    outputMatrix(m, n, Q);
    freeMemory(m, n, Q);
    return 0;
}
 
void allocMemory(int m, int n, double **&Q)
{
    int i;
    Q=new double*[m];
    for(i=0; i<m; i++)
    {
        Q[i]=new double[n];
    }
}
void fillRandomMtrix(int m, int n, double **Q)
{
    int i, j, a;
    for (i=0; i<m; i++)
    {
        for (j=0; j<n; j++)
        {
            a=rand();
            if(a)
            {
                Q[i][j]=rand()%100;
            }
        }
    }
}
 
void findMax(int m, int n, int &mi, int &mj, double **Q)
{
    int i, j;
    mi=0;
    mj=0;
    for(i=0; i<m; i++)
    {
        for(j=0; j<n; j++)
        {
            if(Q[i][j]>Q[mi][mj])
            {
                mi=i;
                mj=j;
            }
        }
        cout<<endl;
    }
}
 
void findMin(int m, int n, int &mi, int &mj, double **Q)
{
    int i, j;
    mi=0;
    mj=0;
    for(i=0; i<m; i++)
    {
        for(j=0; j<n; j++)
        {
            if(Q[i][j]<Q[mi][mj])
            {
                mi=i;
                mj=j;
            }
        }
        cout<<endl;
    }
}
void outputMatrix(int m, int n, double **Q)
{
    int i, j;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
==>         cout<<setw(10)<<setprecision(3)<<Q[i][j]<<''; <==
        }
        cout<<endl;
    }
}
void freeMemory(int m, int n, double **Q)
{
    int i;
    for(i=0; i<m; i++)
    {
        delete[] Q[i];
    }
    delete[] Q;
}

See more:



#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdlib.h>
#include<ctype.h>
using namespace std;

class expression
{
private:
 char infix[100];
 char stack[200];
 int top;
 int r;
 char postfix[100];
public:
 void convert();
 int input_p(char);
 int stack_p(char);
 int rank(char);
};

int expression::input_p(char c)
{
 if( c== '+' || c=='-' )
  return 1;
 else if( c=='*' || c=='/' )
  return 3;
 else if( c=='^')
  return 6;
 else if( isalpha(c)!=0)
  return 7;
 else if( c=='(' )
  return 9;
 else if( c==')' )
  return 0;
 else
 {
  cout<<"Invalid expression ::input error\n";
  exit(0);
 }
}

int expression::stack_p(char c)
{
 if(c=='+' || c=='-')
  return 2;
 else if(c=='*' || c=='/')
  return 4;
 else if(c=='^' )
  return 5;
 else if(isalpha(c)!=0)
  return 8;
 else if(c== '(' )
  return 0;
 else
 {
  cout<<"Invalid expression  ::stack error\n";
  exit(0);
 }
}

int expression::rank(char c)
{
 if(c=='+' || c=='-')
  return -1;
 else if(c=='*' || c=='/')
  return -1;
 else if(c=='^')
  return -1;
 else if(isalpha(c)!=0)
  return 1;
 else
 {
  cout<<"Invalid expression ::in rank\n";
  exit(0);
 }
}

void expression::convert()
{
 cout<<"\n*************************************************\n"
  <<"This program converts the given infix expression\n"
  <<"in to postfix form"
                <<"\n*************************************************\n";
 cout<<"Enter an infix expression ::\n";
 cin>>infix;
 int l=strlen(infix);

 infix[l]=')';
 infix[l+1]='';

 
 top=1;
 stack[top]='(';

 r=0;
 int x=-1;

 int i=0;
 char next=infix[i];

 while(next!='')
 {
  
  while( input_p(next) < stack_p(stack[top]) )
  {
   if(top<1)
   {
    cout<<"invalid expression ::stack error\n";
    exit(0);
   }

   postfix[++x]=stack[top];
   top–-;

   r=r+rank(postfix[x]);
   
   if(r<1)
   {
    cout<<"Invalid expression  ::r<1\n";
    exit(0);
   }
  }

  if(input_p( next ) != stack_p( stack[top]))
   stack[++top]=next;
  else
   top–-;

  i++;
  next=infix[i];
 }
 postfix[++x]='';

 if(r!=1 || top!=0)
 {
  cout<<"Invalid expression ::error in rank or stack\n";
  exit(0);
 }

 cout<<"\n\nThe corresponding postfix expression is ::\n";
 cout<<postfix<<endl;
}

int main()
{
 expression obj;
 obj.convert();
 return 0;
}

1>—— Build started: Project: infix, Configuration: Debug Win32 ——
1>Compiling…
1>infix.cpp
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(94) : error C2137: empty character constant
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(106) : error C2137: empty character constant
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(118) : error C2065: ‘top–’ : undeclared identifier
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(118) : error C2059: syntax error : ‘;’
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(132) : error C2065: ‘top–’ : undeclared identifier
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(132) : error C2059: syntax error : ‘;’
1>z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(137) : error C2137: empty character constant
1>Build log was saved at «file://\\scidc01\bsprof$\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\Debug\BuildLog.htm»
1>infix — 7 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

it is an infix to postfix program:confused:


Thanks for the update:

z:\math\arianfar\mydocs\visual studio 2008\projects\infix\infix\infix.cpp(94) : error C2137: empty character constant

Look at line 94 of infix.cpp — from the «infix.cpp(94)»

infix[l+1]='';

Two quote characters together are not allowed: they are not a character.
I suspect that you mean ‘\0’ as a null terminator character instead. The same will apply to line 106.
Just work though the list looking at each error message in relation to the line itself!

For the «empty character» constants, I don’t think » is valid. If you want the null character, you need to use ‘\0’

or «»

On line 118/132, one of your minus signs in top— is not a minus sign but some other character, causing both errors for those lines.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Я скопировал этот код из учебника, чтобы поиграть с ним, однако продолжал получать сообщение об ошибке, в котором говорилось, что у меня не может быть пустых символьных констант. учебное пособие было в 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

Любая помощь будет оценена

Еще раз спасибо.

1

Решение

Эта строка:

m_pchString[m_nLength-1] = '';

Что вы, вероятно, имеете в виду:

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

Или даже:

m_pchString[m_nLength-1] = 0;

Строки заканчиваются нулем, что записывается как обычный 0 или нулевой символ '\0', Для двойных кавычек "" символ нулевого завершения неявно добавляется в конец, но поскольку вы явно устанавливаете один символ, вы должны указать, какой именно.

9

Другие решения

Что вы думаете о нулевой строке? Да, вы правы, такие строки должны заканчиваться нулем:

m_pchString [m_nLength-1] = 0;

1

Вы сказали, что вы msgstr «получаю ошибку, в которой говорится, что strncpy небезопасно использовать, если я использую нулевой терминатор» но вы используете strlen, который просто не работает если строка не пуста От cplusplus:

Длина строки C определяется завершающим нулевым символом

Я предлагаю вам использовать ноль или 0, как предлагают другие, а затем просто использовать strcpy вместо strncpy так как вы копируете всю строку каждый раз в любом случае.

1

  • Home
  • Forum
  • General Programming Boards
  • C++ Programming
  • empty character constant ??

  1. 12-23-2003


    #1

    o0o is offline


    Registered User

    o0o's Avatar


    Post empty character constant ??

    Hello friends.I am once again bothering u people but what else can I do.I am a beginner.My today’s question is that what is «EMPTY CHARACTER CONSTANT»? and what is its function? thanku.

    People who are angry at my stupid questions can accept my apology but please don’t post any hurting remarks.Thanku v m.


  2. 12-23-2003


    #2

    Fahrenheit is offline


    King of the Internet

    Fahrenheit's Avatar


    ‘\0’ ?

    I don’t really understand what you are saying.


  3. 12-23-2003


    #3

    Prelude is offline


    Code Goddess

    Prelude's Avatar


    >I am once again bothering u people but what else can I do.
    It’s no bother.

    >what is «EMPTY CHARACTER CONSTANT»?
    Two single quotes with nothing in the middle:

    Code:

    int main()
    {
      char c = '';
    }

    This would give you an empty character constant error since such a construct is illegal.

    >People who are angry at my stupid questions can accept my apology
    If somebody flames you for what they perceive to be a stupid question, you can rest assured that they will be flamed by everyone else in return. We don’t operate that way.

    >but please don’t post any hurting remarks.
    One thing you should be aware of is that we won’t coddle you. We just tend to answer questions in the most efficient manner, which tends to come off as rude or cruel. Look past all of that and you will find a great deal of useful information.

    My best code is written with the delete key.


  4. 12-23-2003


    #4

    o0o is offline


    Registered User

    o0o's Avatar


    error?

    If it gives error then y? we use this in some statements?


  5. 12-24-2003


    #5

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    > If it gives error then y? we use this in some statements?
    Like we have any possible idea as to how you’ve messed up the code this time….
    Post some actual code and actual error messages when you get stuck.
    At best, we’ll make random guesses — at worst, we’ll ignore you.


  6. 07-27-2010


    #6

    studychina.net is offline


    Registered User


    Quote Originally Posted by o0o
    View Post

    Hello friends.I am once again bothering u people but what else can I do.I am a beginner.My today’s question is that what is «EMPTY CHARACTER CONSTANT»? and what is its function? thanku.

    People who are angry at my stupid questions can accept my apology but please don’t post any hurting remarks.Thanku v m.

    you just need to add the blank between », it should be like ‘ ‘;it works.
    thank you!


  7. 07-27-2010


    #7

    anon is offline


    The larch


    An answer to a question from 2003!

    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

    Quoted more than 1000 times (I hope).


  8. 07-27-2010


    #8

    CodeMonkey62 is offline


    Registered User


    Quote Originally Posted by anon
    View Post

    An answer to a question from 2003!

    Perhaps they needed time to think about it ?


Popular pages

  • Exactly how to get started with C++ (or C) today
  • C Tutorial
  • C++ Tutorial
  • 5 ways you can learn to program faster
  • The 5 Most Common Problems New Programmers Face
  • How to set up a compiler
  • 8 Common programming Mistakes
  • What is C++11?
  • Creating a game, from start to finish

Recent additions subscribe to a feed

  • How to create a shared library on Linux with GCC — December 30, 2011
  • Enum classes and nullptr in C++11 — November 27, 2011
  • Learn about The Hash Table — November 20, 2011
  • Rvalue References and Move Semantics in C++11 — November 13, 2011
  • C and C++ for Java Programmers — November 5, 2011
  • A Gentle Introduction to C++ IO Streams — October 10, 2011

Similar Threads

  1. Replies: 9

    Last Post: 02-10-2009, 03:50 PM

  2. Replies: 3

    Last Post: 07-15-2007, 12:12 AM

  3. Replies: 5

    Last Post: 06-19-2007, 02:39 PM

  4. Replies: 5

    Last Post: 12-22-2006, 05:45 PM

  5. Replies: 18

    Last Post: 03-29-2004, 05:32 PM

Понравилась статья? Поделить с друзьями:
  • Ошибка emps toyota
  • Ошибка emp dll как исправить rdr 2
  • Ошибка eml на бмв е46
  • Ошибка eml на bmw e53
  • Ошибка eml на bmw e46 что это