3

Location of the error is indicated in a comment below. Please help fix this.

#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class String
{
private:
    enum{sz=80};
    char str[sz];
public:
    String()
    {
        strcpy(str,"");
    }

    String (char s[])
    {
        strcpy(str,s);
    }

    void display() const
    {
        cout<<str;
    }
    String operator +(String ss) const
    {
        String temp;
        if(strlen(str) + (strlen(ss.str) < sz)
        {
            strcpy(temp.str,str);
            strcat(temp.str , ss.str);
        } // Error is reported here!
        else
        {
            cout<<"\nstring overflow";
            exit(1);
        }
        return temp;
    }

};
int main()
{
    String s1="\nMerry christmas";
    String s2="happy new year";
    String s3;

    s1.display();
    s2.display();
    s3.display();

    s3=s1+s2;
    s3.display();
    cout<<endl;
    return 0;
}
moinudin
  • 134,091
  • 45
  • 190
  • 216
Trupti
  • 597
  • 4
  • 8
  • 17
  • What are you using to edit your source code? A good editor will usually point you visually to the right direction. – darioo Dec 20 '10 at 13:10
  • 2
    You do know about the standard library `string` class, right? – jalf Dec 20 '10 at 14:06

3 Answers3

8
if(strlen(str) + (strlen(ss.str) < sz)

should be

if(strlen(str) + strlen(ss.str) < sz)

Notice how you have 4 ( but only 3 ) in the original line. These need to match up, but they don't. Since the ( before the second strlen() is superfluous (there is no need to wrap strlen(ss.str) in brackets), you can remove it.

Original code with changes to the #includes and fixed code. Note that I had to change the #includes from string.h to cstring for ideone. It's the preferred choice anyway. I also had to add using namespace std; as your code wasn't explicitly using the std namepsace where required, e.g. using cout. You should also take care of those warnings.

The reason the compiler error points to 4 lines down is because that's the line where it realises "Oh no, there's a problem here I'm never going to be able to parse this code!" GCC is pretty crappy at error reporting, but a but a compiler (e.g. clang) that does a better job of it would backtrack to the appropriate line where the root cause of the error actually lies and may even suggest a fix for you.

Community
  • 1
  • 1
moinudin
  • 134,091
  • 45
  • 190
  • 216
4

You are missing a right parenthesis at the end of this line:

if(strlen(str) + (strlen(ss.str) < sz)
Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101
4

The error occurs here:

if(strlen(str) + (strlen(ss.str) < sz)

That probably should be:

if (strlen(str) + strlen(ss.str) < sz)
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479