hi
i write this program and i cant solve the errors in program.
in subprogram 'string2.cpp' geting errors of lines 'cin>>s3' and 's2="My name is"+s3'.
what porblems are in 'operator+' and 'operator>>' functions?
Printable View
hi
i write this program and i cant solve the errors in program.
in subprogram 'string2.cpp' geting errors of lines 'cin>>s3' and 's2="My name is"+s3'.
what porblems are in 'operator+' and 'operator>>' functions?
It's not very easy to help you as you didn't post any code - the zip file doesn't have it either.
Post the relevant code here, so we can compile it ourselves, in [ code ][ /code ] tags (but without the spaces). And indicate to us which lines have the compile errors.
thanks
string2.h
string2.cppCode:#ifndef STRING2_H_
#define STRING2_H_
class String
{
private:
char *str;
int len;
static int num_string;
static const int CINLIM=80;
public:
String();
String(const char *s);
String(const String &);
~String();
String& operator+(const String &);
String& operator=(const String &);
String& operator=(const char *);
char& operator[](int i);
const char& operator[](int i)const;
friend bool operator<(const String& st1,const String& st2);
friend bool operator>(const String& st1,const String& st2);
friend bool operator==(const String& st1,const String& st2);
friend ostream& operator<<(ostream &os,const String& st);
friend istream& operator>>(istream &is,String& st);
String& stringlow();
String& stringup();
int has(char ch);
static int HowMany();
};
#endif
stringMian.cppCode:#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
#include "string2.h"
int String::num_string=0;
String::String()
{
str=new char[0];
str=NULL;
len=0;
num_string++;
}
String::String(const char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
num_string++;
}
String::String(const String &st)
{
len=st.len;
str=new char[len+1];
strcpy(str,st.str);
num_string++;
}
String::~String()
{
delete [] str;
num_string--;
}
int String::HowMany()
{
return num_string;
}
String& String::stringlow()
{
for(int i=0;i<=len;i++)
tolower(str[i]);
return *this;
}
String& String::stringup()
{
for(int i=0;i<=len;i++)
toupper(str[i]);
return *this;
}
int String::has(char ch)
{
int count=0;
for(int i=0;i<=len;i++)
//
if(strcmp(&str[i],&ch))
count++;
return count;
}
String& String::operator +(const String &st)
{
char *ch=new char[len];
strcpy(ch,str);
delete [] str;
str=new char[len+st.len+1];
strcat(str,ch);
strcat(str,st.str);
return *this;
}
String& String::operator =(const String& st)
{
if(this==&st)
return *this;
len=st.len;
delete [] str;
str=new char[len+1];
strcpy(str,st.str);
return *this;
}
String& String::operator =(const char *ch)
{
int length=strlen(ch);
if(length==len&&(strcmp(str,ch)==0))
return *this;
len=length;
delete [] str;
str=new char[len+1];
strcpy(str,ch);
return *this;
}
char& String::operator [](int i)
{
return str[i];
}
const char& String::operator [](int i)const
{
return str[i];
}
bool operator<(const String& st1,const String& st2)
{
return (strcmp(st1.str,st2.str)<0);
}
bool operator>(const String& st1,const String& st2)
{
return st2.str<st1.str;
}
bool operator==(const String& st1,const String& st2)
{
return (strcmp(st1.str,st2.str)==0);
}
ostream& operator<<(ostream &os,const String& st)
{
os<<st.str;
return os;
}
istream& operator>>(istream &is,String& st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
st = temp;
while (is && is.get() != '\ n')
continue;
return is;
}
Code:#include <iostream>
using namespace std;
#include "string2.h"
int main()
{
String s1(" and I am a C++ student.");
String s2 = "Please enter your name: ";
String s3;
cout << s2; // overloaded << operator
cin >> s3; // overloaded >> operator
s2 ="My name is "+s3; // overloaded =, + operators
cout << s2 << ".\ n";
s2 = s2 + s1;
s2.stringup(); // converts string to uppercase
cout << "The string\ n" << s2 << "\ ncontains " << s2.has('A')
<< " 'A' characters in it.\ n";
s1 = "red"; // String(const char *),
// then String & operator=(const String&)
String rgb[3] = { String(s1), String("green"), String("blue")} ;
cout << "Enter the name of a primary color for mixing light: ";
String ans;
bool success = false;
while (cin >> ans)
{
ans.stringlow(); // converts string to lowercase
for (int i = 0; i < 3; i++)
{
if (ans == rgb[i]) // overloaded == operator
{
cout << "That's right!\ n";
success = true;
break;
}
}
if (success)
break;
else
cout << "Try again!\ n";
}
cout << "Bye\ n";
return 0;
}
Please be more specific. Compiler errors? Runtime errors? You need to mention exactly what errors you're seeing.
But I took a look at the code, and there are a few issues:
1) There is nothing Visual C++ specific about your code. It is all generic C++ -- next time, post in the non-Visual C++ forum.
2) This is wrong:
The overloaded + is not called, at least the one that you wrote doesn't get called.Code:s2 ="My name is "+s3; // overloaded =, + operators
The + operator in the line above takes a const char* on the left side, and a String on the right of the + sign. This means you have to write an overloaded + operator that takes two parameters:
This must be a standalone function (a friend of the String class).Code:String operator+(const char*, const String &);
3) This is wrong;
This is a memory leak. You're allocating with new[], but then you're losing the pointer by reassigning str. Just because the allocation with new is 0, C++ still must assign a unique pointer from operator new[], regardless of whether it is 0.Code:String::String()
{
str=new char[0];
str=NULL;
len=0;
num_string++;
}
So this one line program is no good:
You wind up calling delete[] on a NULL pointer, but the pointer that you did allocate was never deleted.Code:int main()
{
String s;
}
4) This is not exception safe:
What happens if new[] fails on the second line that's in red? An exception is thrown, so what happened to str? You deleted it, and you can never recover it. This means your String object is in an inconsistent state -- it has a pointer to str that is no good, and the string it used to point to is gone.Code:String& String::operator +(const String &st)
{
char *ch=new char[len];
strcpy(ch,str);
delete [] str;
str=new char[len+st.len+1];
strcat(str,ch);
strcat(str,st.str);
return *this;
}
You do the same mistake here:
You're supposed to allocate everything you need first to a temp pointer, then when finished, you delete [] str and then assign str to the temp pointer. Your code only works as long as new[] doesn't fail, and you don't write classes that use dynamically allocated memory this way.Code:String& String::operator =(const String& st)
{
if(this==&st)
return *this;
len=st.len;
delete [] str; // your string is gone.
str=new char[len+1]; // what if this fails??
strcpy(str,st.str);
return *this;
}
5) This is no good if I pass NULL:
If I pass a NULL pointer to this constructor, you then go ahead and try to get the strlen() of a NULL pointer. If the code doesn't crash, then the behaviour is undefined as to what happens. You're supposed to check first if the pointer is NULL before calling strlen().Code:String::String(const char *s)
{
len=strlen(s);
6) Where is operator += in your code? Any good string class has an operator +=. Instead, you made operator + act as if it is operator +=
The operator + is supposed to return a brand new String, not change the existing string. This goes back to item 2) above. Your String class needs to implement + and +=, and implement versions that take two parameters.Code:String& String::operator +(const String &st); //???
These are just a few of the runtime issues I see with your class.
Also, you do know there is a std::string class that does all of this already, right? So why are you trying to code your own String class, when honestly, writing proper string classes should be left to the advanced (or close to advanced) C++ programmer? If this is homework, there are thousands of examples of String classes, not 100% coded correctly, but still show how to properly overload +, +=, etc. Why not look at those examples?
Regards,
Paul McKenzie
I don't know what error you mean for the line 'cin >> s3', as this line compiles for me. (Whether it runs properly is another matter entirely, but if it doesn't you need to specify what is wrong with it).
As for the second line, 's2="My name is "+s3', this doesn't work because you haven't defined a method to cover adding a string literal ("My name is ") and a String (s3). The methodcan only be used to add two Strings.Code:String& operator+(const String &);
To fix this, you can either use the String constructor 'String(const char *s)', like so:or define this function:Code:s2=String("My name is ")+s3
which will exist outside the String class - it is not a member function, but will need to be a friend to be able to access the String internals.Code:String operator+(const char* lhs, const String& rhs)
In addition, your current operator+ is wrong:It should return a new String, not a reference to 'this' - when you add two things together you get a new thing, after all.Code:String& String::operator +(const String &st)
{
char *ch=new char[len];
strcpy(ch,str);
delete [] str;
str=new char[len+st.len+1];
strcat(str,ch);
strcat(str,st.str);
return *this;
}
Finally, you are trying to create newlines in your output wrongly. '\ n' should be '\n' - no space. Better yet, use std::endl instead.
thanks a lot
these are comiler error.
i try to correct code and i put correct code here. if you see bug in this code, you tell me.
string2.h
string2.cppCode:friend String& operator+(const String &,const String &);
code have comiler errors, for example: "Error3error C2248: 'String::len' : cannot access private member declared in class 'String'c:\documents and settings\fahimeh\my documents\visual studio 2008\projects\test(pr2_chap12)\test\string2.cpp65test"\Code://TRUE
String::String()
{
str=NULL;
len=0;
num_string++;
}
//TRUE
String& operator +(const String & st1,const String &st2)
{
String total;
total.len=st1.len+st2.len+1;
total.str=new char[total.len];
strcat(total.str,st1.str);
strcat(total.str,st2.str);
return total;
}
why cannot access to "total.len" or "total.str"?
the program runs but after take s3 variable, the program stops and the next line not applicable, why?
the operator=() function what do you think instead of code(delete [] str)?
operator=() function is in the C++ primer plus ebook(chapter 12) and this is practice of ebook.
This is wrong.
You are returning a reference to an object that goes out of scope. You cannot return references to local objects. You were already told that operator + returns a brand new string, not a reference.Code:String& operator +(const String & st1,const String &st2)
{
String total;
total.len=st1.len+st2.len+1;
total.str=new char[total.len];
strcat(total.str,st1.str);
strcat(total.str,st2.str);
return total;
}
Code:String operator + (const String& st1, const String& st2)
You have two operator = functions. Which one?Quote:
The operator=() function
Here is what I think -- get another book, a book that preferably teaches C++ in a way where you're writing programs, not fighting with String classes. A book such as "Accelerated C++" is one such book.Quote:
what do you think ...
As far as I know, that book/ebook you're using is obsolete, and you're learning C++ using old, outdated material. It makes no sense to be using material that is:
1) almost 20 years old.
2) Instead of learning, we're correcting obvious mistakes in the book. You can't learn from a book that has these mistakes.
That book teaches C++ in a style that basically went out of style (or should have went out of style) years ago. That book may have had its day back in the early 1990's, but it really shouldn't be used for learning C++ in this day and age. C++ is a language that has evolved from the days when it looked almost exactly like 'C', except for a few keywords. Reading up on up-to-date material (at least material that existed after C++ became standardized in 1998) should be the only consideration when learning the language.
You're supposed to be learning how to write programs that use the C++ library. and only when you have reached intermediate status do you even consider writing classes that have the complexity of String classes. The reason being what you're seeing here on this thread -- you may end up writing a class that is wrong, but "works", and then walk away believing you've written good code when you haven't written such code.
Regards,
Paul McKenzie
acclerated c++ does not appear to be available in ebook