Fruit.h
class Fruit
{
private:
std::int no[3];
public:
void initialize();
int print_type();
};
Fruit.cpp
#include "Fruit.h"
void Fruit::initialize() {
int no[] = {1, 2, 3};
}
int Fruit::print_type() {
return type[0];
}
Main.cpp
#include <iostream>
#include "Fruit.h"
using namespace std;
int main()
{
Fruit ff;
ff.initialize();
int output = ff.print_type();
cout << output;
system("pause");
return 0;
}
Assume the required directives are included inside all the files.
At this moment, I find a problem when getting back the ouput since it will not result in "0" but a garbage value. How can I fix it without using constructor?
Sincerely hope that someone would do me a favor.
This is the way that doesn't use constructors and destructors, I hope you find it useful.
#include <iostream>
class Fruit
{
private : int* no;
public : void initialize();
public : void clean();
public : int print_type();
};
void Fruit::initialize()
{
no = new int[ 3 ];
no[ 0 ] = 1;
no[ 1 ] = 2;
no[ 2 ] = 3;
}
int Fruit::print_type()
{
return no[ 0 ];
}
void Fruit::clean()
{
delete[] no;
}
int main()
{
Fruit f;
f.initialize();
int o = f.print_type();
std::cout << o;
f.clean();
return 0;
}
Please, read about constructor in C++. You don't know about the elementary things in OOP C++.
#include "Fruit.h"
void Fruit::initialize() {
int no[] = {1, 2, 3};
}
This is not correctly. You most write this.no or no.
int Fruit::print_type() {
return type[0];
}
What is variable type?
Related
So I recently started with C at exercism page.
I currently facing a rather simple challenge.
Determine if a word or phrase is an isogram.
An isogram (also known as a "non-pattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
lumberjacks
background
downstream
six-year-old
The word isograms, however, is not an isogram, because the s repeats.
There are 15 tests in total, of which one specific is not passed:
test_isogram_with_duplicated_hyphen
I guess test number 15 also passes because of some error I don't see
Here's the testing code:
#include "test-framework/unity.h"
#include "isogram.h"
#include <stdlib.h>
void setUp(void)
{
}
void tearDown(void)
{
}
static void test_empty_string(void)
{
TEST_ASSERT_TRUE(is_isogram(""));
}
static void test_null(void)
{
TEST_IGNORE(); // delete this line to run test
TEST_ASSERT_FALSE(is_isogram(NULL));
}
static void test_isogram_with_only_lower_case_characters(void)
{
TEST_IGNORE();
TEST_ASSERT_TRUE(is_isogram("isogram"));
}
static void test_word_with_one_duplicated_character(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("eleven"));
}
static void test_word_with_one_duplicated_character_from_end_of_alphabet(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("zzyzx"));
}
static void test_longest_reported_english_isogram(void)
{
TEST_IGNORE();
TEST_ASSERT_TRUE(is_isogram("subdermatoglyphic"));
}
static void test_word_with_duplicated_letter_in_mixed_case(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("Alphabet"));
}
static void test_word_with_duplicated_letter_in_mixed_case_lowercase_first(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("alphAbet"));
}
static void test_hypothetical_isogrammic_word_with_hyphen(void)
{
TEST_IGNORE();
TEST_ASSERT_TRUE(is_isogram("thumbscrew-japingly"));
}
static void
test_hypothetical_word_with_duplicated_character_following_hyphen(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("thumbscrew-jappingly"));
}
static void test_isogram_with_duplicated_hyphen(void)
{
TEST_IGNORE();
TEST_ASSERT_TRUE(is_isogram("six-year-old"));
}
static void test_made_up_name_that_is_an_isogram(void)
{
TEST_IGNORE();
TEST_ASSERT_TRUE(is_isogram("Emily Jung Schwartzkopf"));
}
static void test_duplicated_character_in_the_middle(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("accentor"));
}
static void test_same_first_and_last_characters(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("angola"));
}
static void test_word_with_duplicated_character_and_with_two_hyphens(void)
{
TEST_IGNORE();
TEST_ASSERT_FALSE(is_isogram("up-to-date"));
}
int main(void)
{
UnityBegin("test_isogram.c");
RUN_TEST(test_empty_string);
RUN_TEST(test_null);
RUN_TEST(test_isogram_with_only_lower_case_characters);
RUN_TEST(test_word_with_one_duplicated_character);
RUN_TEST(test_word_with_one_duplicated_character_from_end_of_alphabet);
RUN_TEST(test_longest_reported_english_isogram);
RUN_TEST(test_word_with_duplicated_letter_in_mixed_case);
RUN_TEST(test_word_with_duplicated_letter_in_mixed_case_lowercase_first);
RUN_TEST(test_hypothetical_isogrammic_word_with_hyphen);
RUN_TEST(test_hypothetical_word_with_duplicated_character_following_hyphen);
RUN_TEST(test_isogram_with_duplicated_hyphen);
RUN_TEST(test_made_up_name_that_is_an_isogram);
RUN_TEST(test_duplicated_character_in_the_middle);
RUN_TEST(test_same_first_and_last_characters);
RUN_TEST(test_word_with_duplicated_character_and_with_two_hyphens);
return UnityEnd();
}
This is my code:
#include "isogram.h"
#include <stdlib.h>
#include <stdio.h>
/* gives new char array from input, only small letters */
char* clean_words(char* ptr_input)
{
// new container; everything bigger than 27 is impossible to be an isogram
static char cleaned[27] = {"00000000000000000000000000"};
int i = 0, j = 0, k = 0;
for (int i = 0; ptr_input[i] != '\000'; i++)
{
k++;
}
for (i=0; i <= k; i++, j++)
{
if (ptr_input[i] > 64 && ptr_input[i] < 91)
{
cleaned[j] = ptr_input[i] + 32;
}
else if (ptr_input[i] > 96 && ptr_input[i] < 123)
{
cleaned[j] = ptr_input[i];
}
else
{
j--;
}
}
char* ptr_output = &cleaned[0];
return ptr_output;
}
bool is_isogram(char phrase[])
{
if(phrase == NULL)
{ return false; }
char* ptr_a = clean_words(phrase);
char ca_empty[27] = {"00000000000000000000000000"};
for(int i = 0; i <= 27; i++, ptr_a++){
// first element is always copied
if(i == 0){
ca_empty[i] = *ptr_a;
continue;
}
// '0' is sentinel, meaning the input word is finished => exit loop.
if(*ptr_a == '0' || *ptr_a == '\000')
{ break; }
// following elements only copied if different than current input char
int j = 0;
// loop copied for doubles, exit when found
for(;j<i;j++)
{
if(ca_empty[j] == *ptr_a){
return false;
}
}
// if none was found, copy new letter
ca_empty[i] = *ptr_a;
}
return true;
}
So basically I solve this in 2 steps. First, I will reduce any input to small letters only. Second, I copy letter by letter to a new container and test doubles before every copy process.
Yes, there are certainly fancier solutions, but I'd like to know if anyone can spot why I get FAILED on "six-year-old". Especially, when it is working locally. Thanks! :-)
So I figured it out by myself:
The problem is the helper function clean_words.
The char array cleaned is declared as static. That means it will keep its value even after the current block is finished.
When the tests run through, cleaned will still contain remaining letters of the input from other tests. The solution would be removing the static keywird or implementing a way to clean up the container, like
memset(cleaned, '0', 26);
From https://en.cppreference.com/w/c/language/storage_duration
static storage duration.
The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to main function. All objects declared static and all objects with either internal or external linkage that aren't declared _Thread_local (since C11) have this storage duration.
I'm having difficulty accessing an array of strings. It is declared as a private array and filled in the constructor for the class. I have a Get function defined. The problem is when I call this function at compile time I get an error that I cannot access private member declared in class. I'm just getting back into coding just for the yuks, as such I'm at a stage pre-pointers and pre-vectors so I'm trying to avoid situations that would force their use.
Words.h
#pragma once
#include <string>
#include <iostream>
#include <array>
class Words {
Words();
public:
std::string GetNewWord(int);
private:
std::string WordList[23] = {};
};
Words.cpp - The Array is completely filled but shortened here
#include "Words.h"
Words::Words(){
WordList[0] = "omega";
WordList[1] = "minors";
WordList[2] = "stigma";
WordList[3] = "glamor";
WordList[4] = "savior";
WordList[5] = "disarm";
WordList[6] = "isogram";
.
.
.
;
}
std::string Words::GetNewWord(int choice)
{
return WordList[choice];
}
main.cpp - contains an infinite loop so i could quickly test if the array was populated
#include <iostream>
#include <string>
#include "Words.h"
Words word;
int main() {
do {
std::cout << "choice: ";
int choice;
std::cin >> choice;
std::cout << "\n" << word.GetNewWord(choice) << "\n";
} while (true);
return 0;
}
The constructor is private, as all members of a class are by default. Simply move it to the public section.
Hello i'm trying to fill an array of objects from a text file in c++ , but i have a crash every time i run the program. I'm i at the right direction here? Is there any more eficient way to do it?
main.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include "Item.h"
using namespace std;
void readItems(FILE *products, Item pList[]);
FILE *products;
int main()
{
Item pList[5];
readItems(products,pList);
return 0;
}
void readItems(FILE *products, Item pList[]){
products = fopen("data.txt", "r");
int i = 0;
fread(&pList[i], sizeof(pList), 1, products);
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
fclose(products);
}
Item.cpp
#include "Item.h"
#include <stdio.h>
#include <string>
#include <conio.h>
#include <iostream>
using namespace std;
Item::Item()
{
code = 0;
description = "";
price = 0;
}
Item::Item(int code1,string description1,float price1)
{
code = code1;
description = description1;
price = price1;
}
void Item::printData(){
cout<<endl<<"Code:"<<code<<"\tName:"<<description<<"\tPrice:"<<price;
}
void Item::setData(int code1,string description1,float price1){
code = code1;
description = description1;
price = price1;
}
int Item::getCode(){
return code;
}
float Item::getPrice(){
return price;
}
Item::~Item()
{
//dtor
}
The new code is like that , but it prints a set of some chars of the txt file with some weird symbols .
void readItems(FILE *fin, Item list[]){
int i=0;
products = fopen("items.txt","r");
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
while(!feof(products) && i<5){
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
i++;
}
fclose(products);
}
Try replacing
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
with
while (!feof(products) && (i < 5))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
I have written a straightforward C code that uses an engine to run two different algorithms depending on user input. It uses function pointers to the algorithm methods and objects. There is a nasty memory bug somewhere that I can not track down, so maybe I am allocating memory in the wrong way. What is going wrong?
Below is (the relevant parts of) a minimal working example of the code.
main.c
#include "engine.h"
int main()
{
char *id = "one";
Engine_t eng;
Engine_init(&eng);
Engine_select_algorithm(eng, id);
Engine_run(eng);
}
engine.h
typedef struct _Engine *Engine_t;
engine.c
#include "engine.h"
#include "algorithm_one.h"
#include "algorithm_two.h"
typedef struct _Engine
{
void *p_algorithm;
void (*init)(Engine_t);
void (*run)(Engine_t);
} Engine;
void Engine_init(Engine_t *eng)
{
*eng = malloc(sizeof(Engine));
(*eng)->p_algorithm = NULL;
}
void Engine_select_algorithm(Engine_t eng, char *id)
{
if ( strcmp(id, "one") == 0 )
{
eng->init = Algorithm_one_init;
eng->run = Algorithm_one_run;
}
else if ( strcmp(id, "two") == 0 )
{
eng->init = Algorithm_two_init;
eng->run = Algorithm_two_run;
}
else
{
printf("Unknown engine %s.\n", id); exit(0);
}
eng->init(eng);
}
void Engine_run(Engine_t eng)
{
eng->run(eng);
}
void Engine_set_algorithm(Engine_t eng, void *p)
{
eng->p_algorithm = p;
}
void Engine_get_algorithm(Engine_t eng, void *p)
{
p = eng->p_algorithm;
}
algorithm_one.h
typedef struct _A_one *A_one_t;
algorithm_one.c
#include "engine.h"
#include "algorithm_one.h"
typedef struct _A_one
{
float value;
} A_one;
void Algorithm_one_init(Engine_t eng)
{
A_one_t aone;
aone = malloc(sizeof(A_one));
aone->value = 13.0;
//int var = 10;
Engine_set_algorithm(eng, &aone);
}
void Algorithm_one_run(Engine_t eng)
{
A_one_t aone;
Engine_get_algorithm(eng, &aone);
printf("I am running algorithm one with value %f.\n", aone->value);
// The code for algorithm one goes here.
}
The code for algorithm_two.h and algorithm_two.c are identical to the algorithm one files.
There must be a memory bug involved, because the code runs as given, but if I uncomment the
//int var = 10;
line in algoritm_one.c the code crashes with a segmentation fault.
You pass the wrong thing to Engine_set_algorithm. You are passing the address of a local variable rather than the address of the algorithm. You need to write:
Engine_set_algorithm(eng, aone);
And also Engine_get_algorithm is wrong. You are passed a pointer by value and modify that pointer. So the caller cannot see that modification. You need it to be:
void Engine_get_algorithm(Engine_t eng, void **p)
{
*p = eng->p_algorithm;
}
I think your code would be easier if you defined a type to represent an algorithm. That type would be just a void*, but it would make the code much easier to read. What's more, I would make Engine_get_algorithm return the algorithm.
algorithm Engine_get_algorithm(Engine_t eng)
{
return eng->p_algorithm;
}
void Engine_set_algorithm(Engine_t eng, algorithm alg)
{
eng->p_algorithm = alg;
}
I am newbie in C ,with Mingw32 compiler.
Right now i am creating decompiler from IL to C (Native)
The code generated (Without System.Object):
DecompileTestApplication_Program.c
#include "DecompileTestApplication_Program.h"
DecompileTestApplication_Program* DecompileTestApplication_Program__ctor( ) {
if (array__DecompileTestApplication_Program == 0) {
array__DecompileTestApplication_Program=(void**)malloc(sizeof(void*)*(capacity__DecompileTestApplication_Program=4));
}
DecompileTestApplication_Program* this;
//error: 'this' undeclared (first use in this function)
if (count__DecompileTestApplication_Program==0) {
this=(DecompileTestApplication_Program*)malloc(sizeof(DecompileTestApplication_Program));
goto RealConstructor;
}
this=(DecompileTestApplication_Program*)array__DecompileTestApplication_Program[--count__DecompileTestApplication_Program];
RealConstructor:
this->ind = 0;
this->a = 1;
this->b = 3;
//this._inherit_object_( ); //this is OOP tests ,still working on it
return this;
}
void DecompileTestApplication_Program_Main( ) {
int var_0_02;
var_0_02 = 0;
var_0_02 = ( var_0_02 + 1 );
int var_1_08;
var_1_08 = 1;
int var_2_0A;
var_2_0A = 3;
var_1_08 = ( var_1_08 + var_2_0A );
var_0_02 = ( var_0_02 + ( var_1_08 + var_2_0A ) );
DecompileTestApplication_Program_blat = ( DecompileTestApplication_Program_blat + ++DecompileTestApplication_Program_bpa );
}
void DecompileTestApplication_Program__cctor( ) {
DecompileTestApplication_Program_blat = 1;
DecompileTestApplication_Program_bpa = 4;
}
DecompileTestApplication_Program.h
#ifndef DecompileTestApplication_Program
#define DecompileTestApplication_Program
/*
Type's Name: DecompileTestApplication.Program
Time to Parse: 40.0023ms
*/
#include <stdio.h>
typedef struct {
//Variables
int ind;
int a;
int b;
} DecompileTestApplication_Program;
static int DecompileTestApplication_Program_blat;
static int DecompileTestApplication_Program_bpa;
//Methods
void DecompileTestApplication_Program_Main( );
DecompileTestApplication_Program* DecompileTestApplication_Program__ctor( );
void DecompileTestApplication_Program__cctor( );
static int count__DecompileTestApplication_Program=0;
static int capacity__DecompileTestApplication_Program=0;
static DecompileTestApplication_Program** array__DecompileTestApplication_Program=0;
#endif
#main.h
void main();
#main.cpp
//bookmart for includes
#include "DecompileTestApplication_Program.h"
void main() {
//bookmark for initialize
DecompileTestApplication_Program__cctor();
DecompileTestApplication_Program_Main();
}
The error found in the first file.
I searched the resolve for this error for awhile ,
but didn't found any.
#define DecompileTestApplication_Program
That means that everywhere you see the word DecompileTestApplication_Program, it gets removed. As such, your attempted declaration of this:
DecompileTestApplication_Program* this;
expands to
* this;
which attempts to dereference the undeclared variable this. To fix this, change the macro name.