Trying to make my own string class - c++

These are the errors I'm getting for my program.
myString1.cpp: In constructor ‘MyString1::MyString1(char*, int)’:
myString1.cpp:6: error: expected primary-expression before ‘]’ token
myString1.cpp:6: error: expected primary-expression before ‘]’ token
myString1.cpp: In member function ‘MyString1 MyString1::append(MyString1)’:
myString1.cpp:11: error: invalid use of member (did you forget the ‘&’ ?)
myString1.cpp: In member function ‘void MyString1::clear()’:
myString1.cpp:25: error: expected primary-expression before ‘]’ token
myString1.cpp:25: error: expected primary-expression before ‘{’ token
myString1.cpp:25: error: expected `;' before ‘{’ token
myString1.cpp: In member function ‘bool MyString1::empty()’:
myString1.cpp:29: error: expected primary-expression before ‘]’ token
myString1.cpp:31: error: expected primary-expression before ‘else’
myString1.cpp:31: error: expected `;' before ‘else’
And here is my program in the three different parts.
myString1.h
#ifndef MYSTRING1_H
#define MYSTRING1_H
class MyString1
{
private:
char chars[];
int size;
public:
MyString1();
MyString1(char chars[], int size);
MyString1 append(MyString1 s);
char at(int index);
int length();
void clear();
bool empty();
int find(char ch);
};
#endif
myString1.cpp
#include "myString1.h"
using namespace std;
MyString1::MyString1(char chars[], int size)
{
this->chars[] = chars[];
this->size = size;
}
MyString1 MyString1::append(MyString1 s)
{
for(int i = size; i > size - s.length; i++)
chars[i] = s.at(i);
}
char MyString1::at(int index)
{
return chars[index];
}
int MyString1::length()
{
return size;
}
void MyString1::clear()
{
size = 0;
chars[] = {};
}
bool MyString1::empty()
{
if(chars[]){
return true;
else
return false;
}
}
int MyString1::find(char ch)
{
for(int i = 0; i < size; i++)
if(chars[i] = ch)
return i;
}
testMyString1.cpp
#include <iostream>
#include "myString1.h"
using namespace std;
int main()
{
MyString1 first("cat", 4);
MyString1 second("dog", 4);
cout << first.at(1) << " and " << second.at(1) << endl;
first.append(second);
cout << first.at(6) << endl;
return 0;
}
Im a newbie just trying to learn how to use the g++ compiler so just looking for some help reading the error messages and debugging my code. Also I'm sure there is some very bad code so any help is appreciated.

The code has a lot of mistakes so I don't know where to start from but I suppose that generally giving you some pointers to help you with understanding your code would be okay.
In my opinion you don't need to have a size index in a String class since there is the strlen() function that will gladly compute it for you.
Now for your class declaration check how you declare the pointer that will hold the string for you. You need to do it like below:
class MyString1
{
private:
char* chars;//this declares a pointer to a char that will hold the string for you
public:
...
Also you are never allocating the char* that holds the strings. Your constructor should be:
MyString1::MyString1(const char* chars)
{
this->chars = (char*) malloc(strlen(chars)+1); //this will allocate an array of strlen() chars +1
strcpy(this->chars,chars);
}
As you can see I am not using a size index since strlen can quite efficiently find that out for you. +1 is for the '\0' that signifies the end of a string.
Now to append something to the string, that's gonna be tricky.
void MyString1::append(const MyString1& s) //it's good to give a constant reference to the string here
{
//first of all we gotta reallocate the pointer,since we don't have enough memory for the string
int newsize = strlen(this->chars) + strlen(s)+1;
this->chars = (char*) realloc(this->chars,newSize); \\ no check for realloc failure, I know but this is just an example
strcat(this->chars,s.chars);
}
You don't need to return anything when you append. You are doing something to THIS string.
Your ::at() function is almost okay. Imagine though what would happen if the size of the string was 10 and you request MyString1::at(12). This would probably cause a Segmentation fault (that's not good).
So you should alter your code to do bounds checking like below:
char MyString1::at(int index)
{
//if it's out of bounds let's return -1 which will signify that we got an out of bounds value (could also throw an exception here but that's a different subject altogether)
if(index > strlen(this->chars) || index <0)
return -1;
return chars[index];
}
Also in C/C++ you have to free the memory that you allocate. So in order to do that you should declare something called a destructor
MyString1::~MyString1()
{
free(this->chars);
}
Finally the is empty function can just be like that:
bool MyString1::empty()
{
return (this->chars[0] == '\0';
}

Related

Expected unqualified-id and expected initializer, while declaring function and work with multidimensional array

I'm a newbie at C++, but I tried to do my research.However I seem to be not able to figure out what is wrong in my code, probably not familiar with the syntax, that I can't find. Trying to do something bigger, just testing some theory.
Here I have filled a 2D array, put in a function Func(). Lets suppose I did something to it, then I want to retrieve it from there. I imagined I could extract an address to the first array of arrays, but I keep getting the same error.
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <typeinfo>
using namespace std;
char(*)[15] Func(char A[15][15]) //Here is the problem
{
A[0][0]='O';
return A; //trying to return an address to the A[0]-1D array
}
int main() //This part isn't really important, just filling an 2-D array
{
char A[16][16];
int x,y;
for (y=0; y<=15;y++)
{
for(x=0;x<=15;x++)
{
if (3<=x<=12 and 3<=y<=12)
{
A[y][x]='*';
}
if (x==0 or x==15 or y==0 or y==15)
{
A[y][x]='#';
}
if ((x==2 and 2<=y<=13) or (x==13 and 2<=y<=13) or (y==2 and 2<=x<=13) or(y==13 and 2<=x<=13))
{
A[y][x]='#';
}
if (x==14 or y==14 or (x==1 and y==1))
{
A[y][x]='#';
}
}
}
for (int i=0,y=3, x=1; y<=12; y++, i++ )
{
char j='0'+i;
A[y][x]=j;
}
for (int i=0,y=1, x=3; x<=12; x++, i++)
{
char j='0'+i;
A[y][x]=j;
}
for (y=0; y<=15;y++)
{
for(x=0;x<=15;x++){
cout<<A[y][x];
}
cout<<endl;
}
char(*p)[15]=Func(A[15][15]); //here Im trying to assign pointer p to point to the first 1D array of 15x15 Array of A (To do pointer arithmetics later)
cout<<"p="<<p; //Just testing
return 0;
}
And I get this error:
expected unqualified-id before ')' token
expected initializer before 'Func'
Both directed at Func() function declaration line
Plus this error:
'Func' was not declared in this scope
Which is not pleasant too but less engaging than the previous ones, in my opinion.
I think the problem might be in the type of "A" (the pointer) or there is something I missed.
How can I fix the issues of this code? It feels like I have tried everything! Thank you.
You could use std::array instead. I also fixed the problems mentioned in the comments:
#include <array>
#include <iostream>
using namespace std;
using Field = std::array<std::array<char, 16>, 16>;
Field Func(Field A) //Here is the problem
{
A[0][0]='O';
return A; //trying to return an address to the A[0]-1D array
}
int main() //This part isn't really important, just filling an 2-D array
{
Field A;
int x,y;
for (y=0; y<=15;y++)
{
for(x=0;x<=15;x++)
{
if (3<=x and x<=12 and 3<=y and y<=12)
{
A[y][x]='*';
}
if (x==0 or x==15 or y==0 or y==15)
{
A[y][x]='#';
}
if ((x==2 and 2<=y and y<=13) or (x==13 and 2<=y and y<=13) or (y==2 and 2<=x and x<=13) or(y==13 and 2<=x and x<=13))
{
A[y][x]='#';
}
if (x==14 or y==14 or (x==1 and y==1))
{
A[y][x]='#';
}
}
}
for (int i=0,y=3, x=1; y<=12; y++, i++ )
{
char j='0'+i;
A[y][x]=j;
}
for (int i=0,y=1, x=3; x<=12; x++, i++)
{
char j='0'+i;
A[y][x]=j;
}
for (y=0; y<=15;y++)
{
for(x=0;x<=15;x++){
cout<<A[y][x];
}
cout<<endl;
}
auto p = Func(A); //here Im trying to assign pointer p to point to the first 1D array of 15x15 Array of A (To do pointer arithmetics later)
cout<<"p=\n";
for (const auto &row : p) {
for (const auto &el : row)
cout << el; //Just testing
cout << '\n';
}
return 0;
}
You need C's "declaration follows use" principle.
You would access a single array element of the result as
(*Func(some_array))[x]
so the prototype would be
char (*Func(char A[15][15]))[15]
But it's slightly more readable to use a type alias instead.
For instance,
using FifteenChars = char[15];
FifteenChars* Func(FifteenChars A[15])
{
return A;
}
There are a few other issues:
There is a conflict between your array sizes.
A[15][15] is not the top left part of A but a single char, the one in the bottom right corner.
3<=x<=12 is not 3<=x && x<=12, but (3<=x)<=12, and 3<=x converted to int is either 0 or 1.
You need to spell it out, or split the loop into several individual parts.

Getting error while trying to copy STL Set into Vector

I am trying to initialize vector by already preset Set but getting error
vector<string> findRepeatedDnaSequences(string s) {
int size = s.length();
set<string>container;
unordered_map<string,int>hmap;
for(int i=0;i<size;i++){
string first=s.substr(i,10);
if(hmap.find(first)!=hmap.end()){
// if((i-hmap[first])>=10)
container.insert(first);
}else hmap[first] = i;
}
// ERROR IN THIS LINE
return vector<string>res(container.begin(), container.end());
}
anagrams.cpp:21:26: error: expected '(' for function-style cast or type construction return vector<string>res((container.begin(), container.end()));

access private member variable through private member, same class

// M9P369.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
const int MaxSize = 100;
using namespace std;
class Set {
int len; // number of members
char members[MaxSize]; // the set is stored in this array
int find(char ch); // find an element
public:
Set() { len = 0; } // constructor to make a null set initially
int getLength() { return len; } // return number of elements in the set
void showset(); // display the set
bool isMember(char ch); // check for membership
Set operator+(char ch); // overload operator to add an element to the set
Set operator-(char ch); // overload operator to remove an element from the set
Set operator+(Set ob2); // set Union - overloaded by the different type from above overload+ function
Set operator-(Set ob2); // set difference same as above.
};
// Return the index of the element passed in, or -1 if nothing found.
int Set::find(char ch) {
int i;
for (i=0; i < len; i++)
if (members.[i] == ch) return i;
return -1;
}
// Show the set
void Set::showset() {
cout << "{ ";
for (int i=0; i<len; i++)
cout << members[i] << " ";
cout << "}\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
I am learning operator overloading, and came across a class access problem.
The line
if (members.[i] == ch) return i;
Gives a tooltip error 'expression must have class type', and compile errors:
\m9p369.cpp(34): error C2059: syntax error : '['
\m9p369.cpp(40): error C2228: left of '.showset' must have class/struct/union
\m9p369.cpp(41): error C2228: left of '.cout' must have class/struct/union
I am defining the private member function find() of class Set, and I get the error upon trying to access the private member char array of the same class, members. Error seems to say I should specify which class it's referring to, why? I already specify the class in the definition:
int Set::find(char ch) {
As I understand, members should be in the scope of the function definition. I looked hard for any stray characters I couldn't find anything odd, all parenthesis seem to match.
Problem is here:
members.[i]
It should be just
members[i]
Remeove the . from
if (members.[i] == ch) return i;
~~~~~~~~~~~^

need help on #include doesn't seem to be working

So I have a class called HPStack and I have to include it in my main class etc. However I get a "In File included from" error, what could be causing this?
Also my string objects also have errors I have have no idea why, the error is: "Unable to identifier string".
I'm new the C++ so any help would be appreciated, thanks in advance.
The error I am getting (I think) are these:
error: expected unqualified-id before "namespace"
error: expected `,' or `;' before "namespace"
error: expected namespace-name before ';' token
error: `<type error>' is not a namespace
Im not sure what I am missing but that isn't telling me much.
Here is my code: The class.h file.
#ifndef HPSTACK_H
#define HPSTACK_H
class HPStack {
public:
HPStack();
void push(double);
double pop();
double peek();
private:
double register_[4];
}
#endif
The class.cpp file.
#include "HPStack.h"
#include <cstdlib>
HPStack::HPStack() : register_{}{
}
double HPStack::push(double x) {
for (int i = 2; i >= 0; i--) {
if (isdigit(register_[i])) {
register_[i] = register_[i + 1];
}
register_[0] = x;
}
}
double HPStack::pop() {
return register_[0];
for (int i = 0; i < 3; i++) {
register_[i] = register_[i + 1];
}
}
double HPStack::peek() {
return register_[0];
}
And my main file:
#include "HPStack.h"
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
HPStack stack;
string line;
while (getline(cin, line)) {
stringstream expression(line);
string token;
while (expression >> token) {
if (isdigit(token[0])) {
stack.push(atof(token.data()));
} else if (token == "+") {
double x = stack.pop();
double y = stack.pop();
double z = (y + x);
stack.push(z);
}
}
cout << stack.peek();
}
The error is, I'm guessing, because of this line:
double register_[4] = {};
You can not initialize class members when declaring them.
If your compiler is new enough to support C++11 features, you can use an initializer list with the constructor:
HPStack::HPStack()
: register_{}
{
}
Otherwise you have to initialize the array manually in the constructor.
And as I noted in a comment, using register_ - 2 makes no sense as it returns a pointer so the index variable i will be way beyond the end of the array.
And using register_ - 1 as the condition in the pop loop makes even less sense, as it will always be non-zero and therefore always true and the loop will loop forever.
You're missing the ; at the end of the class definition:
class HPStack {
...
}; // <== This semicolon is required

list as member in a class

I am having some trouble! My goal is to check an input number against a list of prime numbers to see if it is prime (in the list) via the find() function. I haven't gotten that far yet. This is homework so I have to overload the function operator and do it in this dumb (imho) way. Here is what I have thus far:
using namespace std;
class isprime {
public: isprime() { /*nothing...yet?*/
}
bool operator()(int);
list <int> pnums(1, 2);
private: int expandList(int number);
};
bool isprime::operator()(int number) {
if (pnums.back() < number) {}
}
int isprime::expandList(int number) {
for (int j = pnums.back(); j = number; j++) {
for (int i = 2; i < sqrt(j); i++) {
if (j % i != 0) pnums.push_back(j);
}
}
}
int main() {
isprime pcheck;
int number;
while (cin >> number) {
if (pcheck(number)) cout << number << " is prime!\n";
}
}
Here are my errors:
prime2.cpp:12: error: expected identifier before numeric constant
prime2.cpp:12: error: expected ',' or '...' before numeric
constant prime2.cpp: In member function 'bool
isprime::operator()(int)': prime2.cpp:19: error:
'((isprime*)this)->isprime::pnums' does not have class type
prime2.cpp: In member function 'int isprime::expandList(int)':
prime2.cpp:23: error: '((isprime*)this)->isprime::pnums' does not have
class type prime2.cpp:25: error:
'((isprime*)this)->isprime::pnums' does not have class type
I don't understand what is going wrong. Could anyone help me out?
The biggest problem is how you are trying use the constructor for the list in your class. If you simply remove (1, 2) from the list declaration in your class, it should compile. Second, if you want to call the constructor of an object in your class, I recommend this method
class isprime{
public:
isprime() : pnums(1,2) { /*nothing...yet?*/ }
...
list <int> pnums;
...