Hi!
Here is my task:
Write class Word which has:
*pointer on array of characters
*constructors and destructors
*function to read word
*function to check if character which is passed to it as argument occurs in word and return position of occurance
*function to check which of two words has more occurances of number 10 and to return that number of occurances
Here is my solution. I compiled it without errors but it doesn't work as it should. See comments
Mderators note : Please use code tags for pieces of code
Here is my task:
Write class Word which has:
*pointer on array of characters
*constructors and destructors
*function to read word
*function to check if character which is passed to it as argument occurs in word and return position of occurance
*function to check which of two words has more occurances of number 10 and to return that number of occurances
Here is my solution. I compiled it without errors but it doesn't work as it should. See comments
Code:
#include <iostream>
#include <string.h>
using namespace std;
class Word{
private:
char *content;
int length;
public:
Word();
Word(char *);
~Word();
void print_content(void);
int check_character(char);
friend int check_number(Word,Word);
};
Word::Word(){
}
Word::Word(char *n){
length=strlen(n);
content=new char [length];
for(int i=0;i<length;i++){
content[I]=n[I];
}
}
Word::~Word(){
delete content;
}
void Word::print_content(void){
for(int i=0;i<length;i++){
cout<<""<<content[I];
}
}
int Word::check_character(char a){
int position=0;
for(int i=0;i<length;i++){
if(content[I]==a){
position=i+1;
}
}
if(position>0){
return position;
}
else return 0;
}
int check_number(Word n,Word m){
int counter_n=0;
int counter_m=0;
for(int i=1;i<n.length;i++){
if((n.content[i-1]=='1')&&(n.content[I]=='0')){
counter_n=counter_n+1;
}
}
for(int i=1;i<m.length;i++){
if((m.content[i-1]=='1')&&(m.content[I]=='0')){
counter_m=counter_m+1;
}
}
if(counter_n>counter_m){
return counter_n;
}
else if(counter_n<counter_m){
return counter_m;
}
else return 0;
}
int main()
{
char characters1[]="qwerty10",*p1,*p2;
char characters2[]="10allab10outcirc10uits";
p1=characters1;
p2=characters2;
Word first(p1);
Word second(p2);
cout<<""<<first.check_character('h')<<endl;
cout<<""<<second.check_character('z')<<endl;
//cout<<""<<check_number(first,second)<<endl; //This function for some reason makes other functions to work incorrectly, if you call it here you will see that first.print_content() and
//second.print_content() don't give us correct result. Or if function firstly first.check_character('r') is first called, second.check_character('j') second called and then check_number(first,second), then two firsly called functions don't work.
//What's reason for this strange behaviour?
first.print_content();
second.print_content();
}
Last edited by a moderator: