code won't run..can't run the bool function - c++

I have the following code:
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
using namespace std;
class sekuence
{
public:
sekuence() {
string emra[5][20];
int m=0;
}
void shto (){
int i;
int j;
char temp[20];
cout << "=============================="<<endl
<< "Shkruani emrat qe doni te shtoni ne vektor"<<endl;
for(i=0; i < 5; i++){
cin >> emra[i];
m++;
}
for(i=0; i<5; i++)
{
for( j=1; j<5; j++){
if(strcmp(emra[j-1],emra[j]) > 0) {
strcpy(temp,emra[j-1]);
strcpy(emra[j-1],emra[j]);
strcpy(emra[j],temp);
}
}
}
}
void print(){
for(int i=0; i<5 ; i++){
cout<<endl<<emra[i];
}
cout <<m;
}
bool kerko (const char *gjej)
{
for(int i=0; i<5; i++)
{
if(strcmp(emra[i],gjej) == 0 )
return true;
return false;
}
}
int n (){return m;}
private:
int m;
char emra[5][20];
};
int main()
{ char* gjej;
int x;
sekuence d;
do{
cout<<endl << " =========================" << endl;
cout<<"1 - Funksioni i shtimit" <<endl;
cout<<"2 - Funksioni i afishimit" <<endl;
cout<<"3 - Funksioni i kerkimit" <<endl;
cout<<"4 - Funksioni i fshirjes" <<endl;
cout<<"5 - Dalje nga programi" <<endl<<endl;
cout<<"====================================" <<endl;
cin >> x;
switch (x)
{
case 1:
d.shto();
break;
case 2:
d.print();
break;
case 3:
cout<<"==================================" <<endl
<< "Shkruani emrin qe doni te kerkoni"<<endl;
cin >> gjej;
d.kerko(gjej);
break;
case 4:
break;
case 5:
cout << "Dalje nga Programi" <<endl;
exit (0);
default:
cout <<"Zgjedhje e gabuar";
return 0;
}}
while (x != 5);
return 0;
}
Everytime I try to run the bool function I get an error..i don't what to do.
when i try to enter the nam i want to fine the function bool kerko() and quit the prog. and want find the char i want to find it opens the visual studio debugger.

You are trying to access gjej (char*) but no memory allocated to it. Try allocating some memory using new
char* gjej = NULL;
gjej = new char[NumberOfChars];
Edit: used new instead of malloc now..
std::string would be even nicer..

According to your indentation of the kerko function, one of the return statements should be moved out of the for loop:
bool kerko (const char *gjej)
{
for(int i=0; i<5; i++)
{
if(strcmp(emra[i],gjej) == 0 )
return true;
}
//*** Note the new location.
return false;
}
The layout you have makes the bool function always return before the 2nd iteration of the loop.

Related

End a while loop that continue ask for string input until I enter -1

I have to create a menu that holds item names, I can do it with a for loop that ends until the max has been reach, but how do I do it with a while loop that will continue ask until the max is reached or I enter -1
I tried with a for loop and it worked, but I have to use a while loop that can stop when I tell it to stop.
#include <iostream>
using namespace std;
void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
int MAX_MENU_ITEMS);
int main()
{
const int MAX_MENU_ITEMS = 5;
char menu_list[MAX_MENU_ITEMS][50];
float price_list[MAX_MENU_ITEMS];
int num_menu_items;
read_in_menu(menu_list, price_list, num_menu_item, MAX_MENU_ITEMS);
}
void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
int MAX_MENU_ITEMS)
{
for (int i = 0; i < MAX_MENU_ITEMS; i++)
{
cout << "Enter Names: ";
cin.getline(menu_list[i], 20);
}
}
I want to use a while loop that will continue going until I input -1 or reach the maximum. I want to stop the while loop whenever I want instead of the for loop where I have to reach the max.
If I understand correctly, something like this should work:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS || input == "-1") {
cout << "Enter Names: ";
cin.getline(input, 20);
if(input != "-1") { //to avoid setting menu_list[i] = "-1"
menu_list[i] = input;
}
MAX_MENU_ITEMS++;
}
or using break:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS) {
cout << "Enter Names: ";
cin.getline(input, 20);
if(input == "-1") {
break;
}
menu_list[i] = input;
MAX_MENU_ITEMS++;
}
Whenever you want to exit a loop you can use the break keyword.
for(int i = 0; i < MAX; i++){
if(i > 10){
break;
}
doWork();
}
I was able to get it with a pointer lol.
void read_in_menu(char menu_list[5][20], float price_list[], int &num_menu_items, int MAX_MENU_ITEMS){
int i = 0;
char *p = "-1";
while(i<MAX_MENU_ITEMS){
cout << "Enter Name" << endl;
cin.getline(menu_list[i],20);
if(strcmp(menu_list[i], p)){
i++;
}else{
break;
}
}
}
You can transform for loop to other loops. For example:
For
for(int i = 0; i < 10; i++)
DoSomething();
While
int i = 0;
while(i < 10){
DoSomething();
i++;
}
do-while
int i = 0;
do{
DoSomething();
i++;
}
while(i < 10);
To control the loops use continue and break keywords. Keyword continue will skip the current iteration of the loop and break will exit the loop. These are usually conditioned by if statement.

invalid types 'int[int]' for array subscript in multidimensional array c++

While doing my course project of card game, i got this error
Invalid types `int[int]' for array subscript'
Here is the code :
#include <iostream>
#include <stdlib.h>
#include <time.h>
int randomize(int, int);
int* generateCardNumber(int[5]);
int* generateCardLogo(int, int[13][4], int[5]);
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
int printResult(int[5]);
void showCard(int, int[5], int[5], int[5], int[5]);
void printCard(int[5], int[5]);
using namespace std;
int main()
{
srand(time(NULL));
int player1Number[5], player1Logo[5];
int *number1, *logo1;
int player2Number[5], player2Logo[5];
int *number2, *logo2;
int cardInfo[13][4];
int **card;
char answer;
do
{
int playerInput;
int d, c, r;
int player1Score, player2Score;
cout<<"Welcome to the card game!"<<endl;
cout<<" Choose player{1: Player 1; 2: Player 2} : ";
cin>>playerInput;
cout<<endl;
do
{
cout<<"Press d to deal card :";
}while(d != 'd');
number1 = generateCardNumber(player1Number);
logo1 = generateCardLogo(1,cardInfo, player1Number);
for (int i = 0; i<5; i++)
{
cardInfo[player1Number[i]][player1Logo[i]] = 1;
}
number2 = generateCardNumber(player2Number);
logo2 = generateCardLogo(2,cardInfo, player2Number);
for (int i = 0; i<5; i++)
{
cardInfo[player2Number[i]][player2Logo[i]] = 1;
}
showCard(playerInput,player1Number,player1Logo,
player2Number,player2Logo);
do
{
cout<<"Press c to compare card :";
}while(c != 'c');
*card = compareCard(player1Number,player1Logo,
player2Number,player2Logo,cardInfo);
for (int i = 0; i<5; i++)
{
if(cardInfo[player1Number[i]][player1Logo[i]] = -1)
{
player1Number[i] = -1;
player1Logo[i] = -1;
}
else if(cardInfo[player2Number[i]][player2Logo[i]] = -1)
{
player2Number[i] = -1;
player2Logo[i] = -1;
}
}
showCard(playerInput,player1Number,
player1Logo,player2Number,player2Logo);
do
{
cout<<"Press r to show result :";
}while(r != 'r');
if(playerInput == 1)
{
cout<<"Player1 (You): ";
player1Score = printResult(player1Number);
cout<<"Player2 (Computer): ";
player2Score = printResult(player2Number);
if(player1Score > player2Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer): ";
player1Score = printResult(player1Number);
cout<<"Player2 (You): ";
player2Score = printResult(player2Number);
if(player2Score > player1Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
cout<<"Do you want to play again? (y/n)"<<endl;
cin>>answer;
}while(answer == 'Y' || answer == 'y');
}
int randomize (int x, int y)
{
return (rand()%y + x);
}
int* generateCardNumber (int numberArray[5])
{
int arrayStoring[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i<5; i++)
{
do
{
numberArray[i] = randomize(1,13);
}while (arrayStoring[numberArray[i]] == 1);
arrayStoring[numberArray[i]] = 1;
}
return numberArray;
}
int* generateCardLogo (int turn, int cardInfo[4][13], int player2Number[5])
{
int logoArray[5];
if(turn == 1)
{
for (int i = 0; i<5; i++)
{
logoArray[i] = randomize(1,4);
}
return logoArray;
}
else if(turn == 2)
{
for (int i = 0; i<5; i++)
{
do
{
logoArray[i] = randomize(1,4);
}while (cardInfo[player2Number[i]][logoArray[i]] == 1);
}
return logoArray;
}
}
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
{
for(int j=0; j<5 ; j++)
{
if(player1Number[i] == player2Number[j])
{
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
else if(player1Logo[i] > player2Logo[j]) cardInfo[player2Number[i]][player2Logo[i]] = -1;
break;
}
}
}
return cardInfo;
}
int printResult (int playerNumber)
{
int playerScore = 0;
for (int i = 0; i<5; i++)
{
if(playerNumber[i] == -1) break;
else if(playerNumber[i] == 0)
{
playerScore += 15;
cout<<"15 ";
}
else if(playerNumber[i] > 0 && playerNumber[i] < 10 )
{
playerScore += (playerNumber[i] + 1);
cout<< (playerNumber[i] + 1) <<" ";
}
else if(playerNumber[i] >= 10)
{
playerScore += 12;
cout<<"12 ";
}
if(i<4) cout<<"+ ";
else if(i==4)
{
cout<<"= "<<playerScore<<" points";
}
}
return playerScore;
}
void printCard (int numberArray[5], int logoArray[5])
{
for (int i = 0; i<5; i++)
{
switch(numberArray[i])
{
case -1 :
cout<<"<fold> ";
break;
case 0 :
cout<<"Ace ";
break;
case 1 :
cout<<"2 ";
break;
case 2 :
cout<<"3 ";
break;
case 3 :
cout<<"4 ";
break;
case 4 :
cout<<"5 ";
break;
case 5 :
cout<<"6 ";
break;
case 6 :
cout<<"7 ";
break;
case 7 :
cout<<"8 ";
break;
case 8 :
cout<<"9 ";
break;
case 9 :
cout<<"10 ";
break;
case 10 :
cout<<"Jack ";
break;
case 11 :
cout<<"Queen ";
break;
case 12 :
cout<<"King ";
break;
}
switch(logoArray[i])
{
case -1:
break;
case 0:
cout<<"Diamond ";
break;
case 1:
cout<<"Club ";
break;
case 2:
cout<<"Heart ";
break;
case 3:
cout<<"Spade ";
break;
}
}
}
void showCard (int playerInput, int player1Number, int player1Logo, int player2Number, int player2Logo)
{
if(playerInput == 1)
{
cout<<"Player1 (You):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (Computer):"<<endl;
printCard(player2Number, player2Logo);
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (You):"<<endl;
printCard(player2Number, player2Logo);
}
}
Honestly, i still newbie at programming. So i didn't know that i can't return a whole array from a function. After searching for clue, i found out that i can use pointer to return an array from function. When i try to fix the code, this error come out and i didn't know what i need to fix.
The error keep appearing when i try to use the array from the function parameter,such as this
if(player1Number[i] == player2Number[j])<br/>
from function
int** compareCard(int player1Number, int player1Logo, int player2Number,
int player2Logo, int cardInfo)
and onward.
Can someone help me figure this out? Correction to the code would be very appreciated. Thankyou very much! (Sorry if my english is bad)
You're declaring compareCard with a bunch of arrays (so int pointers) as parameters:
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
Then, however, you're implementing it using integers (not pointers) as parameters:
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
You're also using them as arrays:
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
Also, the return type is wrong. You're declaring it as int*, but then implement it as int**. You have to ensure that the signature of your function matches. It looks like taking the signature of the declaration and applying it to the definition should fix this compile time error.
Does your compiler issue any warnings for these function declarations? If not, see if you can set it to be more strict with warnings. Getting the correct warnings for potential errors greatly increases debug efficiency.

BinarySearch function not working

I've got a menu that I've been working on, and everything now seems to work, except for the binary search function. I am entering the size of the array, filling the array, printing it, then sorting it with my chronological menu, and then when I do sequential search, it seems to work. However, binary search does not even return -1 to indicate that the number was not found, the program just stops. Suggestions? Thanks.
#include<iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int size=0; //global variable size
int a[100]; //global array
int getSize()
{
cout << "Array Size: ";
cin >> size;
return size;
cout << endl;
}
int sequentialSearch(int n)
{
for(int i=0;i<size;i++)
{
if(n==a[i])
{
return (i+1);
}
}
return -1;
}
int binarySearch(int n)
{
int low=0,high=size,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==n)
{
return mid+1;
}
else if(a[mid]>n)
high=mid-1;
else if(a[mid]<n)
low=mid-1;
}
return -1;
}
void sort1()
{
int i, j;
for (i = 0; i < size-1; i++)
{
for (j = 0; j < size-i-1; j++)
if (a[j] > a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
void sort2()
{
int i, j, m;
for (i = 0; i < size-1; i++)
{
m = i;
for (j = i+1; j < size; j++)
{
if (a[j] > a[m])
m = j;
}
int temp=a[m];
a[m]=a[i];
a[i]=temp;
}
}
void printMenu()
{
cout<<"0. Exit\n";
cout<<"1.Get the size needed for todays use of the array \n";
cout<<"2.Fill an array with random numbers from 1-100 \n";
cout<<"3.Print the array with position numbers \n";
cout<<"4.Sort the array in ascending sequence \n";
cout<<"5.Sort the array in descending sequence \n";
cout<<"6.Sequential search of the array for a target\n";
cout<<"7.Binary search of the array for a target\n";
}
void printTheArray()
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<" is at position :"<<i+1<<endl;
}
}
void fillWithRandom()
{
for(int i=0;i<size;i++)
{
int x=rand()%101;
a[i]=x;
}
}
void dispatch(int ch)
{
switch(ch)
{
case 1:cout<<"Size of array :"<<getSize() << endl;
break;
case 2:fillWithRandom();
break;
case 3: printTheArray();
break;
case 4:sort1();
break;
case 5:sort2();
break;
case 6:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res1=sequentialSearch(t);
if(res1!=-1)
cout<<"Found in position :"<<res1<<endl;
else if(res1==-1)
cout<<"Not Found \n";
break;
}
case 7:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res=binarySearch(t);
if(res!=-1)
cout<<"Found in position :"<<res<<endl;
else if(res==-1)
cout<<"Not Found \n";
break;
}
default:cout<<"wrong choice\n";
}
}
int main ()
{
printMenu();
int choice;
cout<<"Type in a choice"<<endl;
cin>>choice;
while(choice!=0)
{
dispatch(choice); // one big switch statement
printMenu();
cout<<"Type in a choice"<<endl;
cin>>choice;
}
cout << endl;
// wrap-up
cout << "This program is coded by Troy Wilms" << endl; // fill in your name
// stops the program to view the output until you type any character
return 0;
}
for example, if you try finding 4 in list {1, 3, 5}, low will be always 0 and high will be always 2. because of the code 'low = mid - 1' I think it should be changed to 'low = mid + 1'

CodeBlocks .exe has stopped working

my .exe well compiled program stops working after run it in CodeBlocks,
It stops after typing cin>>f.name the to the console after the choosed choice
I have a Windows 8 and i use GNU GCC compiler here is the code,maybe there is a code error , i don t know
tanks for your attention
:
using namespace std;
struct employee
{
string name;
int age;
};
employee employeeList[10];
class Stack
{
int pos;
public:
Stack(){};
void push(employee e)
{
employeeList[pos] = e;
pos++;
}
employee pop(int n)
{
if(n = pos - 1)return employeeList[pos];
if(n < pos - 1)
{
return employeeList[pos];
for(int j =n; j < pos; j++ )
{
employeeList[pos] = employeeList[pos + 1];
}
}
pos--;
}
string print(int n)
{
n = pos;
cout<<employeeList[pos].name<<endl;
}
char menu()
{
char choice;
cout << "Press 1. to push an employee"<<endl;
cout << "Press 2. to pop an employee"<<endl;
cout << "Press 3. to show an employee"<<endl;
cin>> choice;
return choice;
}
};
int main()
{
Stack s;
char input = s.menu();
int j;
do
{
switch(input)
{
case '1' :{employee f; cin>>f.name; s.push(f);}break;
case '2' :{int n; cin>>n; s.pop(n);} break;
case '3' :{int n; cin>>n; s.print(n);}break;
}
j++;
}
while(j < 10);
return 0;
}
You didn't proper initialization of instance variable "pos" of class "Stack". This means that initially it can have any value. If that value is beyond the range of your "employeeList", you are accessing an area of memory that does not belong to you. That's probably a segmentation error.

deciding if a number is perfect or prime

the problem is :
"Write a function to find out if a number is a prime or perfect number."
so far i have worked on the perfect part first and this is what i have:
#include <iostream>
using namespace std;
bool perfectNumber(int);
int main()
{
int number;
cout<<"Please enter number:\n";
cin>>number;
bool perfectNumber(number);
return 0;
}
bool perfectNumber(int number)
{
int i;
int sum=0;
for(i=1;i<=number/2;i++)
{
if(number%i==0)
{
sum+=i;
}
}
if (sum==number)
return i;
else
return 0;
}
HOWEVER, there seems to be errors on this code.
I have looked over the book but nothing talks about this topic.
i would like to get advice on how to fix this code.
thanks!
bool perfectNumber(number);
This does not call the perfectNumber function; it declares a local variable named perfectNumber of type bool and initializes it with the value of number converted to type bool.
In order to call the perfectNumber function, you need to use something along the lines of:
bool result = perfectNumber(number);
or:
bool result(perfectNumber(number));
On another note: if you are going to read input from a stream (e.g. cin>>number), you must check to be sure that the extraction of the value from the stream succeeded. As it is now, if you typed in asdf, the extraction would fail and number would be left uninitialized. The best way to check whether an extraction succeeds is simply to test the state of the stream:
if (cin >> number) {
bool result = perfectNumber(number);
}
else {
// input operation failed; handle the error as appropriate
}
You can learn more about how the stream error states are set and reset in Semantics of flags on basic_ios. You should also consult a good, introductory-level C++ book for more stream-use best practices.
void primenum(long double x) {
bool prime = true;
int number2;
number2 = (int) floor(sqrt(x));// Calculates the square-root of 'x'
for (int i = 1; i <= x; i++) {
for (int j = 2; j <= number2; j++) {
if (i != j && i % j == 0) {
prime = false;
break;
}
}
if (prime) {
cout << " " << i << " ";
c += 1;
}
prime = true;
}
}
bool isPerfect( int number){
int i;
int sum=0;
for(i=1;i<number ;i++){
if(number %i == 0){
cout<<" " << i ;
sum+=i;
}
}
if (sum == number){
cout<<"\n \t\t THIS NUMBER >>> "<< number <<" IS PERFECT \n\n";
return i;
}else if (sum |= number) {
cout<<"\nThis number >>> " << number <<" IS NOT PERFECT \n\n";
return 0;
}
}
#pragma hdrstop
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
//---------------------------------------------------------------------------
bool is_prim(int nr)
{
for (int i = 2; i < nr-1; i++) {
if (nr%i==0) return false;
}
return true;
}
bool is_ptr(int nr)
{
int sum=0;
for (int i = 1; i < nr; i++) {
if (nr%i==0) {
sum=sum+i;
}
}
if (sum==nr) { return true;
}
else return false;
}
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
int numar;
printf ("Number=");scanf("%d",&numar);
if (is_prim(numar)==true) { printf("The number is prime");
}
else printf("The number is not prime");
if (is_ptr(numar)==true) { printf(" The number is perfect");
}
else printf(" The number is not perfect");
getch();
return 0;
}