using std::string;
using std::streamsize;
using std::setprecision;
using namespace std;
int main()
{
double Ib,I,V,P,F,pf,In;
unsigned short int type;
cout<<"Please select the type of power supply\n";//Allows the user to choose between single or three phase
cin>>type;
switch(type)
{
case 1:cout<<"You have chosen a single phase power supply\n";
break;
case 2:cout<<"You have chosen a three phase power supply\n";
break;
default:cout<<"Invalid choice please try agin\n";
break;
}
cout<<"Please enter the value of I\n";//the value of the load current
cin>>I;
cout<<"Please enter the value of V\n";//the value of the input volatge
cin>>V;
cout<<"Please enter the value of F\n";//the frequency
cin>>F;
cout<<"Please enter the value of the power factor\n";//the power factor
cin>>pf;
if(type=1)
{
cout<<"Ib in Single phase is\n" << setprecision(4)
<<(V*I)/V/I/pf
<<setprecision(4)<<endl;
else
cout<<"Ib in Three phase is\n" << setprecision(4)
<<(V*I)/(1.732*V*pf)
<<setprecision(4)<<endl;
}
Hello, i am very interested in the c++ language, i decided to make my own small program and test how arrays work with classes with private variables and private operations and then calling them any way i'd like from the main function.
a very big reason about this is probably because i'm trying to pass by reference, which i thought was necesary if i'm keeping the changes everywhere within the program, and using a void function. If there is any advice as to coding better, i'd like those too.
there are syntax errors, line 20 only, please help me :)
////.header file for class arrays.
#include <string>
using namespace std;
class arrays {
private:
string hold;
int keep;
int raekwon[];
public:
void Talk(string&, int&);
};
///this is my arrays header function
#include "arrays.h"
void arrays::Talk(hold&, keep&) {
///this creates the array based from the size parameter
raekwon[keep];
//this displays the information
cout << "okay, you are feeling " << hold << " today.\n";
cout << "also, the size of the array you asked for is " << keep << "\n";
cout << "the elements in the array are: " << raekwon << "\n";
Hello,
I'm stuck with this code and I can't figure out how to make it work. I need to get the Sum of Odd numbers from an array. For some reason it returns 0.
I'm new to programming, so any help would be appreciated, thanks.
Here it is:
#include <iostream>
using namespace std;
const int MAX = 10;
int a[ MAX ] = {1,2,3,4,5,6,7,8,9,10};
int smallResult = 0;
int sumOdd( int MAX[], int n )
{
if ( n == 0 )
return 0;
else{
int smallResult = sumOdd( MAX + 1, n - 1 );
return smallResult + MAX[ 0 ];
}
}
int main ()
{
cout << "Sum of Odd is: " << smallResult << endl;
return 0;
}
Hi guys and gals, 1st post here! Woot!
With that out of the way, I need some help with this steaming fresh BJ program. I need to write functions for the yes deal and no deal options, but the player total seems to get messed up somehow and when a new card is added after the fist two, the total becomes the second card + the first card. I need a little help figuring out what would be the problem.
if (opto == 'N' || opto == 'n')
{
if (toty > totd || toty == totd)
{
cout << "You win!\n"<< toty << " is more than or equal to " << totd << endl;
break;
}
else
{
cout << "The house wins!\n" << totd << " is more than " << toty << endl;
break;
I am working on an assignment which is a container class that uses an array to hold strings. We must use dynamic memory, and can only use cstring class functions, no objects can be strings. So we must use char arrays. Anyways my problem is that whenever i run my program it instantly crashes and I can't seem to find why, any help would be greatly appreciated.
/*
* stringArray.h
*
* Created on: Mar 2, 2010
* Author: Jacob
*/
//Constructor for the stringArray class
// stringArray(const size_t max_size = DEFAULT_SIZE);
//
//
//Copy constructor stringArray(const stringArray& source);
//
//Destructor ~stringArray();
//
//bool addString(const char new_string[]);
// adds a new string in the bag.
// POSTCONDITION: returns true if string was successfully added to the bag, false otherwise
//
//bool removeString)const char old_string[]);
// removes one occurrence of old_string from the bag.
//POSTCONDITION: returns trus if successful; false otherwise
//
//size_t removeAll(const char old_string[]);
//removes all occurrences of old_string from the bag.
//POSTCONDITION: removes the strings and then returns the number of strings removed
//
//bool substitute(const char old_string[], const char new_strin[]);
//Replaces one occurrence of old_string with new_string
// POSTCONDITION: one is replaced and true is returned, if there are no occurences of old_string
// or the function failed somehow, false is returned instead
//
//size_t substituteALL(const char old_string[], const char new_stringn[]);
// Replaces all the occurrences of old_string with new_string
//POSTCONDITION: Returns the number of strings replaces.
//
//size_t size()
// returns the total number of strings in the bag
//
// bool is_string(const char cur_string[]) const;
// returns true if cur_string is present in the bag, false otherwise
//
// size_t occurrences(const char cur_string[]) const;
// returns the number of occurrences of cur_string in the bag
//
// void printStringArray() const;
// Prints out all strings in the stringArray object, one string per line
//
// void pringSortedStringArray() const;
// prints out all strings in the stringArray object, one string per line, ina sorted order from least to greatest
//
// overloaded operators
//
// stringArray operator+ (stringArray& x, stringArray& y)
//
// stringArray operator- (stringArray
#include <iostream> // Provides ostream and istream
#include <cstdlib> // Provides ostream and istream
stringArray::stringArray(const size_t max_size)
//creates a dynamic array that is the size of the max size
//sets count equal to zero
{
char** storage = new char* [max_size];
for(int i = 0; i < max_size; i++)
{
storage[i] = "\0";
}
count = 0;
}
stringArray::stringArray()
{
char** storage = new char* [10];
for(int i = 0; i < 10; i++)
{
storage[i] = "\0";
}
count = 0;
}
stringArray::~stringArray()
{
for(int i = 0; i < max_size; i++)
{
delete storage[i];
}
delete storage;
}
Hi, i am doing my mom's c++ for engineering class, and doing a project for her, i noticed something in the extra credit section of her project directions. it says to add graphics to represent what variables the users are entering. in this one, it is about beam deflection, and it says for extra credit to put a diagram of the beam and the parts labeled with the variables. How would i go about doing this?
I have downloaded a library from this site that deals with Matrix and Complex........Does it do this correctly??? http://www.zenautics.com/matrixdoc/index.html
if so I want to use this library to get the inverse matrix of of a matrix consists of a complex elements
how can I do this???
If it is a wrong one
can any one help me to get a library do this function please
thanks in advance
I am trying to set up a 12 month table summary in a bank account program. The problem I have is I am trying to figure out how to set it up correctly. Here is my class and application from the bank account:
//Constructor method: a special method used to
//initialize an object's state
//The constructor is automatically called and executed
//when the object is instantiated
void SavingsAccount::setAccount(int accNo, double startBalance, double startRate)
{
accountNumber = accNo;
balance = startBalance;
rate = startRate;
}
double SavingsAccount::getBalance()
{
cout << "\nThe current balance in your account is $"
<< balance << endl;
return balance;
}
string SavingsAccount::deposChoice()
{
cin.ignore();
cout << "\nWould you like to make a deposit(Y/N): ";
getline(cin, depositChoice);
return depositChoice;
}
double SavingsAccount::depositBalance()
{
if (depositChoice == "Y")
{
cout << "\nEnter amount to deposit: ";
cin >> deposit;
return deposit;
}
else if (depositChoice == "N")
{
cout << "\nOk no deposit I see!"
<< endl;
}
}
string SavingsAccount::withdrawChoice()
{
cin.ignore();
cout << "\nWould you like to make a withdrawal(Y/N): ";
getline(cin, withdrawalChoice);
return withdrawalChoice;
}
double SavingsAccount::withdrawalBalance()
{
if (withdrawalChoice == "Y")
{
cout << "\nEnter amount to withdrawal: ";
cin >> withdrawal;
return withdrawal;
}
else if (withdrawalChoice == "N")
{
cout << "\nOk no withdrawal I see!"
<< endl;
}
}
double SavingsAccount::getEndingBalance()
{
if (depositChoice == "Y" && withdrawalChoice == "Y")
{
endBalance = balance + deposit - withdrawal;
cout << "\nThe ending balance for your account is $"
<< endBalance << endl;
return endBalance;
}
else if (depositChoice == "Y" && withdrawalChoice == "N")
{
endBalance = balance + deposit;
cout << "\nThe ending balance for your account is $"
<< endBalance << endl;
return endBalance;
}
else if (depositChoice == "N" && withdrawalChoice == "Y")
{
endBalance = balance - withdrawal;
cout << "\nThe ending balance for your account is $"
<< endBalance << endl;
return endBalance;
}
else if (depositChoice == "N" && withdrawalChoice == "N")
{
endBalance = balance;
cout << "\nThe ending balance for your account is $"
<< endBalance << endl;
return endBalance;
}
}
Here's the cpp/application part:
#include <iostream>
#include<string>
#include <iomanip>
using namespace std;
#include "SavingsAccount.h"
//file is located in project directory
int main()
{
cout << "Welcome to the bank today!" << endl;
cout << "\nMONTH START BALANCE INTEREST END BALANCE\n";
int month;
double interest = 0.0;
double endBalance = 0.0;
double rate = 0.0;
double newEndBalance = 0.0;
month = 1;
while (month <= 12)
{
interest = endBalance * rate;
newEndBalance = endBalance + interest;
cout << month << endBalance << interest << newEndBalance << endl;
month++;
}
cout << "\nThanks for stopping by the bank, have a nice day!\n" << endl;
return 0;
}//END MAIN
The output of the table is supposed to be like this:
Month Starting Interest Ending
# Balance Earned Balance
1 4000.00 16.00 4016.00
2 4016.00 16.06 4032.06
3 ... ... ...
4
5
6
7
8
9
10
11
12
The start balance of is table is the ending balance after I deposited/withdrew funds, the interest part I have to multiply the balance to the rate(.004) and the end balance is where I have to add the balance to interst.
The table part of it is the last part of the cpp part, I just wanted to know what to put there to make it come out correctly. Thanks greatly for the help.
hello guys this is my first attempt in C++ and i am getting an error :(
the programs is made to read 20 numbers and find how many of them are even (like 2,4,6,20,40)
#include <iostream>
using namespace std;
int c[20];
int s = 0;
int i = 1;
int main()
{
cout << "Enter the numbers followed by the ENTER key\n";
loop:
cin >> c[i];
if(c[i]%2=0) //line with error
{s++;}
i++;
if (i<=20) goto loop;
cout << "done!\n Number of values: ";
cout << s;
system("PAUSE");
return 0;
}
and the error:
In function `int main()'
line 14: error: non-lvalue in assignment
CustData is a structure that is declared, and the name data member of that struct is of type string. For some reason when I call this function(there are no compile errors), it displays the cout statement, but then completely skips over the getline function. Any ideas?
I read some time back that memory operation on stack is much faster than heap. With this information the first thing came into my mind was that if we get a way to allocate memory dynamically on stack it would surely help us to optimize memory operation cost. I started searching for it and finally I found one such way ;).
Before going into its detail let’s take a look at dynamic memory allocation on heap.
Generally when it comes to dynamic memory allocation new/malloc the well known calls
Comes into mind. They help us to dynamically allocate memory on the heap.
For e.g.
int FunctionA()
{
char* pszLineBuffer = (char*) malloc(1024*sizeof(char));
…..
// Program logic
….
free(pszLineBuffer);
return 1;
}
Above code would allocate 1024 bytes on heap dynamically. After the complete use of variable szLineBuffer, we
need to free memory also (free/delete can be used for it). So, one has to keep track of deallocation call,
else memory leak will get introduced.
Now coming back to our question, is there any way by which we can allocate memory dynamically on stack.So the answer is yes. We can allocate variable length space dynamically on stack memory by using function _alloca. This function allocates memory from the program stack. It simply takes number of bytes to be allocated and
return void* to the allocated space just as malloc call. This allocated memory will be freed automatically on function exit.
So it need not to be freed explicitly. One has to keep in mind about allocation size here, as stack overflow exception may occur. Stack overflow exception handling can be used for such calls. In case of stack overflow exception one can use _resetstkoflw() to restore it back.
So our new code with _alloca would be :-
int NewFunctionA()
{
char* pszLineBuffer = (char*) _alloca(1024*sizeof(char));
…..
// Program logic
….
//no need to free szLineBuffer
return 1;
}
Now let’s check out what will be the advantage of _alloca over new/malloc :-
1) We have saved overhead of new/malloc.
As _alloca() got very little overhead of allocating memory on stack.
2) No need to free memory explicitly. So, deallocation cost will be zero.
3) If function like FunctionA() got multiple time in your program it may cause heap memory fragmentation on a long run,
Which would be saved with NewFunctionA() as stack memory never goes fragmented.
Now let’s check out what will be the disadvantage of _alloca over new/malloc :-
1) One has to be cautious while using alloca for huge blocks.
2) Its scope is limited to a function call.
3) As stack overflow is not a standard C++ exception, one hast to use structured exception handling for it.
One can also right ask that :-
"_alloca function is deprecated because a more secure version is available.
_malloca : Allocates memory on the stack. This is a version of _alloca with security enhancements."
My Answer to this question is :-
"malloca does not allocates memory from stack always, it will go to heap depending on _ALLOCA_S_THRESHOLD value. Also you need to manage its deallocation flow. _alloca is best suited to be used when you need small chunk of memory but very frequently and if chuck size is not guaranteed to be small _malloca can be used.
One more point _malloca always allocates memory from the heap in DEBUG mode. So you get diffrent behavior in release and debug."
NOTE:- I have added hyperlink in accordance to rule, which says :-
"Self-promotion links are permitted within forum signatures provided they do not contradict with any other sitewide rules, such as inappropriate language or content." So is it ok?
I'm really interested in C++ and am currently making a basic Text based poker game.
on a sideline to this does anyone know any simple encryption code or where to start when doing this? For instance taking a text file (.txt or even .doc?) and creating your own encryption key and encrypting and decrypting.
Also wonder about password protection and things like this.
1. Manipulate dynamic pointers and arrays of pointers
2. Use sorts, strings, searches and string functions.
Procedure:
1. Your new software engineering group is hired for its first paying project to develop a console application to demonstrate a possible user interface for a next generation MP3 player.
2. Your C++ program will prompt the user to input up to 20 (controlled with a global constant int) names of Artists whose songs will be loaded into the MP3 player. No artist name will be more than 80 characters (including the null terminator). Each entry needs to be loaded (strcpy would be nice) into a dynamic string created with the new keyword.
3. Each of the pointers to the strings of the Artists names needs to be stored in an array – yielding an “array of pointers”.
4. The array needs to be sorted in a separate void function such that the first alphabetical artist name should be stored in the [0] entry of the array, the next in the [1] entry etc.
5. After the array is sorted, call a void function passing the array and the number of entries in the array and print out the artists. The list should be sorted correctly.
6. After printing out the artists, prompt the user for a search string in main(). Call a void function to search through the strings pointed to by your array and return (through a call by reference) an array of references which contain the search string. The search should be case in sensitive. If you searched, for example, on “bob”, you would return references to “Bob Dylan” and “The bobs”.
7. If there were valid references returned from your search, call the same print function as in step 5 above and print out the artists that had a match in the search. If there were no valid references, cout a message to the user. You should allow for multiple searches via re prompting.
8. At the end of your program be sure to iterate through your newly allocated strings and be sure to return the allocated memory back to the operating system.
9. Here’s an example of input and output:
Enter artist name: Grateful Dead
Another artist? (y,n): y
Enter artist name: Lucinda Williams
Another artist? (y,n): y
Enter artist name: Third Eye Blind
Another artist? (y,n): y
Enter artist name: Bob Marley
Another artist? (y,n): y
Enter artist name: Metallica
Another artist? (y,n): n
Sorted Artist List:
Bob Marley
Grateful Dead
Lucinda Williams
Metallica
Third Eye Blind
Enter search string: ll
References:
Lucinda Williams
Metallica
Search Again? (y,n): y
Enter search string: a
References:
Bob Marley
Grateful Dead
Lucinda Williams
Metallica
Search Again? (y,n): y
Enter search string: x
Sorry. No references in database for search on: "x"
Search Again? (y,n): n
Press any key to continue
Basically I am trying to learn multithreading in C++. Platform: Windows XP. So far so good but I want to make sure I'm using mutex correctly. It compiles and runs as expected, but just wanted to make sure I use the CreateMutex() function in the correct place.
I am curious about how to post or have published tutorials. I have searched the forum but the latest information I cna find is years out of date. Any help here?
Hello, I've been searching for hours now for a way to do mouse movement in a program while its minimized, so I can do other stuff etc while the mouse movements are doing their thing in the target window.
Could anyone please give me a direction how to do this?
this is srini... is any one clear me the concept of BIT FIELDS........and what is necessity to use?????
explain the below program..........i hope i can get a good reply from the great members
// BIT FILED //
#include<iostream.h>
#include<conio.h>
struct word
{
unsigned w0:1,w1:1,w2:1,w3:1,w4:1,w5:1,w6:1,w7:1,w8:1,w9:1,w10:1,w11:1,w12:1,w13:1,w14:1,w15:1,w16:1,w17:1,w18:1,w19:1,w20:1,w21:1,w22:1,w23:1,w24:1,w25:1,w26:1,w27:1,w28:1,w29:1,w30:1,w31:1;
};
union set
{
word m;
unsigned u;
};
void main()
{
set x,y;
x.u=0x0f100f10;
y.u=0x01a1a0a1;
x.u=x.u|y.u;
cout<<"element 9="<<((x.m.w9)?"true":"false")<<endl;
}
I am trying to understand a C++ code.
In one part of the code a one dimensional vector is copied into a two dimensional vector.
I do not understand at all how such thing can work. But compiler is quite ok with that.
#define TOTAL_STEPS 120
#define NUMBER_DECISION_VARIABLES 5
int main(){
I programming a telnet server that has to display text in color. The color codes are ANSI escape sequences ie characters. These characters when passed to ostringstream via << mess up setw() formatting alignment.
I need a mechanism to receive and process escape sequence characters from operator << without passing them on to ostringstream. What is the best way to do this?
I could write a wrapper that emulates ostringstream but then I would have to provide every overloaded << function. That's a lot of busy work. There has to be a better way.
Last night, I tried to inherit public ostringstream and provide operator << for my color class. I realized that would not work because ostringstream operator<< returns a reference to ostringstream and not my class. Could I overload operator << in color() to return console()? How would that translate into code?
class console: public std::ostringstream
{
public:
console& (operator<<) ( color &c )
{
std::cout << "color: " << c.i << std::endl;
}
// wont work if color is not the first obj passed to the stream
};
Next I tried to emulate the entire ostringstream interface. This works except for setw, which gives me compile error "error: declaration of 'operator<<' as non-function" in g++.
#include <iostream>
#include <iomanip>
using std::setw;
Working on my pacman project I have come across something strange. Im using the outline font method from NeHe and have used the code from there for text printing. When I copied it to my main method and texted it worked fine. But a lot of my objects need to print text so I decided to move the code to a text printing object. I didn't change anything in the text code but now that it's been moved when glPrintf() is called the symbol printed is one less than the one asked (e.g: "w" prints "v", "!" prints a space) I have tried to rectify it by adding 1 to the variables in the method but nothing works.
It's not a big problem as I can work around it but for printing the score it is a big problem.
Here are the h and cpp files for it:
//Header file for text printer
#ifndef TEXTPRINTER_H_
#define TEXTPRINTER_H_
#include <windows.h> // Header File For Windows
#include <math.h> // Header File For Windows Math Library
#include <stdio.h> // Header File For Standard Input/Output
#include <stdarg.h> // Header File For Variable Argument Routines
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <gl\glaux.h> // Header File For The Glaux Library
class textPrinter
{
private:
GLuint base; // Base Display List For The Font Set
GLfloat rot; // Used To Rotate The Text
GLYPHMETRICSFLOAT gmf[256]; // Storage For Information About Our Outline Font Characters
public:
GLvoid BuildFont(GLvoid); // Build Our Bitmap Font
//Class file for textPrinter
//Note: This code is taken from NeHe tutorial 14: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=14
#include "textPrinter.h"
GLvoid textPrinter::BuildFont(GLvoid) // Build Our Bitmap Font
{
HFONT font; // Windows Font ID
this->base = glGenLists(256); // Storage For 256 Characters
font = CreateFont( -12, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_BOLD, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch
"Comic Sans MS"); // Font Name
SelectObject(wglGetCurrentDC(), font); // Selects The Font We Created
wglUseFontOutlines( wglGetCurrentDC(), // Select The Current DC
0, // Starting Character
255, // Number Of Display Lists To Build
this->base, // Starting Display Lists
0.0f, // Deviation From The True Outlines
0.2f, // Font Thickness In The Z Direction
WGL_FONT_POLYGONS, // Use Polygons, Not Lines
gmf); // Address Of Buffer To Recieve Data
}
GLvoid textPrinter::KillFont(GLvoid) // Delete The Font
{
glDeleteLists(this->base, 256); // Delete All 256 Characters
}
GLvoid textPrinter::glPrint(const char *fmt, ...) // Custom GL "Print" Routine
{
float length=0; // Used To Find The Length Of The Text
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
for (unsigned int loop=0;loop<(strlen(text));loop++) // Loop To Find Text Length
{
length+=gmf[text[loop]].gmfCellIncX; // Increase Length By Each Characters Width
}
glTranslatef(-length/2,0.0f,0.0f); // Center Our Text On The Screen
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(this->base); // Sets The Base Character to 0
glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
}
I have the following classes, SLList, an integer datatype-based linked list and DLList, a template-based linked list. My problem is that SLList is working perfectly, but as soon as i modify it to be used as a template, i get errors, more specifically LNK 2019, i.e. linking errors. I avoided the use of pointers and have been up all night trying to fix it. Please help:
SLList.h:
#ifndef SLLIST_H
#define SLLIST_H
#include <iostream>
using namespace std;
class ListNode
{
public:
int data;
ListNode *next;
ListNode *previous;
ListNode(){next = previous = NULL;}
ListNode(int d, ListNode *p = NULL, ListNode *n = NULL)
{
data = d;
previous = p;
next = n;
}
};
class SLList
{
private:
ListNode *head, *tail;
int length;
public:
SLList();
~SLList();
bool isEmpty();
bool isInlist(int data);
void addToHead(int data);
void addToTail(int data);
int removeTail();
int removeHead();
bool deleteData(int data);
void clearList();
friend ostream &operator<<(ostream &os, SLList& list);
};
i'm currently taking c++ courses in my college and have been noticing that i'm having trouble grasping the fundamentals of programming or even understanding the concepts that are being taught. the courses are taught with no textbook whatsoever so going back for references leaves me with my lecture notes and the internet which can be confusing. so i just wanted to know what books have been helpful to you in understanding c++.
Hi, I am fairly new to C++ but love to learn, so I wanted to create a simple program base on the group-party game mafia A.K.A "werewolf."
Just so whoever is not familiar gets the background. I will use just an example of 10 players. In a ten player game, there consists of 4 roles and this is how many there will be in the game:
3 Mafia
1 Cop
1 Doctor
5 Innocent
I figured I would assign those roles "randomly" to each player using those limits. So
0= mafia, 1= cop, 2= doctor, and 3 = innocent
I got somewhat of the code running ok only when generating a 3 player game. I only know how to use a bunch of "IF's" statement, if anyone knows how to make things easier, please feel free to teach me. When I try to compile a 10 player game, after getting all the player's names, the program just goes to a blank new line and nothing happens.
int main()
{
int numOfPlayers = getNumOfPlayers();
char playerName[numOfPlayers][256];
So basically, playerName[0] will be player[0],
playerName[1] will be player[1],
Oh, This user will be playing this as playerName[0], and the rest of the players will be computers.
The game continues in 2 Phases, a NIGHT time, and a DAY time.
During the NIGHT time, the mafia's will choose first who do they want to "kill, or get rid of" How should I write it that the mafia's will know who each other is, and if all the mafias are computers, they will randomly choose a person to kill other than mafias. If there is a 1 to 1 ness where more people are chosen, then it loops until there is a majority vote. They can only kill 1 per NIGHT time. The Cop then gets to choose who to investigate and find out their ROLES, this knowledge comes in handy. The Doctor, gets to choose who does he want to heal, which will negate the kill of a mafia if the same person gets chosen.
DAY TIME:
The revealed person whom the Mafia choose is announced dead.
Everyone Gets to vote who they think is the mafia. Of course mafias won't vote for mafias, and the COP will know who is innocent so he won't vote for that person. These votes will all be randomized unless stated above.
Then display who each person voted for.
Whoever gets the most vote, gets killed, reveal their role.
Show how many players are left, and what roles.
REPEAT NIGHT and DAY
Until All Mafias are killed, OR the # of Mafia's are equal to # of The others combine.
Whew, that was long, So, is this writable?? Or is it too much?
Thanks for any help!
Hi,
I need to make application that will act as server and have clients. computers with client will get permission to go to internet or not via server. Only permission to go but they will connect directly on net (not a firewall). Its some sort of internet cafe management depending on time. Once time is out, server should send "sign" to client which will block the internet connection.
I want it to be un-terminable via task manager. So any ideas on where to start?
Thanks :)
Right now i am having difficulty skipping the blank lines in the txt file i read in. I read in all the material i need, but the blank lines come in too and messes up my array.
this is my txt file
####
#M##
#..#
##.#
#..#
####
0
S
E
S
W
0
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
ifstream dataFile;
dataFile.open("mice.txt");
char maze[10][10];
//char direction[10][1];
int i=0;
int j=0;
char output;
I just did this and I am not sure I am doing this correctly.
You have purchased a stereo system that cost $1000 on the following credit plan: no payment down, an interest of 18% per year, and monthly payments of $50. The monthly payment of $50 is used to pay the interest and whatever is left is used to pay part of the remaining debt. Hence, the first month you pay 1.5% of $1000 in interest. That is $15 in interest. So, the remaining $35 is deducted from your debt, which leaves you with a debt of $965.00. And its asking for total payment and total interest.
cout << "The speed of in minutes and seconds per mile is: " << spm << " minutes and " ;
cout << spmRemainder << "seconds.";
getch();
}
I have having trouble with this problem. Can you guys advise? I am not sure I am doing this right but this is what I have now. I searched around there was one using while loop. I am not sure if its necessary. I am using Borland btw. Thanks in advance
I want to know how does the IP Messenger work? How does it detect all the available online users?
I searched on the web but due to Cyberoam restriction, I am left with very few options. I go by IP Addresses too, but even then I am not getting the desired information.
I am trying to find the yield of a bond given the bond price, coupon, and semiannual three yr bond using newtons method. The value for B in the output should about equal 101. I have checked everywhere for errors but cant find any. Any ideas?
And yes I am aware about my vectors but dont make fun, i dont know how to automate them.
// bondyield.cpp : Defines the entry point for the console application.
//
Rational fractions are of the form a/b, where a and b are integers and b≠0. Suppose a / b and c / d are fractions. Arithmetic operations on fractions are defined by the following rules:
a/b + c/d = (ad + bc) / bd
a/b – c/d = (ad – bc) / bd
a/b x c/d = (ac)/(bd)
(a/b) / (c/d) = ad/bc, where c/d ≠0
Fractions are compared as follows:
a/b op c/d if ad op bc, where op is any of the relational operators. For example, a/b < c/d if ad < bc.
Design a class, FractionType, that performs the arithmetic and relational operations on fractions. Overload the arithmetic and relational operators so that the appropriate symbols can be used to perform the operation. Also, overload the stream insertion operator and stream extraction operator for easy input and output.
Write a C++ program that uses the FractionType class to perform operations on fractions. Note that your answers do not need to be in lowest terms.
I am trying to compile a code that utilises an array of 5 'hotel' objects as below:
#include "Hotel.h"
using namespace std;
int main()
{
Hotel *hotels = new Hotel[5];
hotels[0] = new Hotel("Hershey");
hotels[1] = new Hotel("Milton");
hotels[2] = new Hotel("Sheraton");
hotels[3] = new Hotel("BestWestern");
hotels[4] = new Hotel("DaysInn");
for(int i = 0; i < 5; i++)
hotels[i].print();
return 0;
}
Hotel.h:
#ifndef HOTEL_H
#define HOTEL_H
#include "DLList.h"
#include <string>
using namespace std;
class Hotel
{
private:
char *name;
DLList<char *> *guestList;
int guestCount;
My problem is that on compilation I get the following:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 11
Error 2 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 12
Error 3 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 13
Error 4 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 14
Error 5 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Hotel *' (or there is no acceptable conversion) ...\app.cpp 15
any suggestions?
I have inlcuded all the code i have on it. Sorry, haven't commented it but is simple enough for any one with intermediate knowledge of c++ to figure out, my appologies in advance :p
I need to create a function that uses a loop.
This function will open a text file and then must be able to skip a variable number of leading random integers. The program must be able to handle any number of leading random integers.
Example if the opened file reads this on its first line:
100 120 92 82 38 49 102
and the SKIP_NUMBER variable is assigned 3 the number the function would grab is 82.
The function must continue to grab the integers every SKIP_NUMBER until it reaches the end of the file.
These integers taken from the txt file are then placed into another text file.
Please help I'm really lost on how to create this loop! :D
Here is my finction so far...
________________________________________-
//Function skips variables and returns needed integer
int skipVariable (int SKIP_NUMBER)
{
return 0; //temporary return
}
____________________________________
These are my program variables:
// initalize function/variables
ifstream fin;
string IN_FILE_NAME, OUT_FILE_NAME;
int SKIP_NUMBER;
Hi,
I'm trying to create a vector array that contains pointers, and these pointers point to objects(particles) that have been created while the program is running.
How do I use the appropriate de-reference operator to use functions of the class particle?
ex. particle.move();
Here is what I have and my guess:
#include <vector>
#include <particle.h>
void main() {
vector <particle*> vect_a;
vect_a.push_back(new particle);
*(vect_a[0]).move();
}
Here, the compiler doesn't think i've declared 'move', but particle.move() works fine outside of the vector of pointers.
I need help. In my assignment i have an input file that contains string data: ----> i love music and chicken. today is the first day of the rest of your life. my name is john.
I must change it to the following in the output file: ----> I love music and chicken. Today is the first day of the rest of your life. My name is john.
I need to use this function to help achieve this:
void initialCap(string&);
No classes are required.
All the white space is erased initially that's why i use the insert function. However, the last word "john" is erased when i use this function. How do i increase the size of the string in order to still have john included in the output. I realize string is an array and arrays are immutable but i know there has to be a way around this. Also, I can't capitalize the words i need to capitalize. I need to use the replace function but, i'm not sure how the parameters work.
Any help is greatly appreciated
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void initialCap(string&);
int main () {
ifstream inputFile;
inputFile.open("C:/Notepad++/input.txt");
ofstream outputFile;
outputFile.open("c:/Notepad++/output.txt");
string baseSentence = "";
string str2 = " dave";
if (inputFile) {
while (!inputFile.eof()) {
string str1 = baseSentence;
str1.insert(0," ");
inputFile>>baseSentence;
cout<<str1;
outputFile<<baseSentence;
}
}
else {
cout<<"this file does not exist dave!";
}
Ok what im tryin to do is open a file by the name a user request after that i ask the user and id number to look for in the file if its found i want to display it along with the name after it but i cant figure out how to get it to display the name and id num if its not found then gives the user the option to add it to the file and then look again for another id num..... please help
/*************************************************************************************
** File name : lab6_driver.cpp
**
** This program will open and read a file then ask user for an ID to look up and then display if its found or not.
**
**
**
** Programmer : Christopher Erb
**
** Date Created : 02/26/10
**
** Date last revised:
************************************************************************************/
#include <iostream> // Need for cout,cin
#include<iomanip> // Need setf,fixed,showpoint,setprecision
#include <stdio.h> // Need for getchar
#include <fstream> // Needed for files
#include <cstdlib> // Needed for exit function
#include <string> // Need for string class
using namespace std;
string getInputFileName(); // a function to prompt for the complete file name
int getId(); // Function that gets the id number
void search(ofstream& outFile, ifstream& inFile, int);
int main ()
{
ofstream outFile;
ifstream inFile;
string fileName; // complete file name including the path
fileName = getInputFileName(); // prompt and obtain the full file name
// try to open the file
outFile.open(fileName.c_str(),ios::in | ios::out | ios::app);
inFile.open(fileName.c_str(),ios::in);
if (!inFile.is_open())
{
cerr << "File open error " ;
cout << " Press enter to continue" << endl;
cin.ignore();
char ch = getchar();
exit (1);
}
if(!outFile.is_open())
{
cerr << "File open Error Creating file" ;
cout << " Press enter to continue" << endl;
cin.ignore();
char ch = getchar();
exit(1);
}
cout << " Press Enter to continue" << endl;
cin.ignore();
char ch = getchar();
return 0;
}
//************************************************************
//
// Function name: getInputFileName
//
// Purpose: to prompt for the fully qualified name of a file
// i.e. including the path of the file
//
// Input parameters: none
//
// Output parameters: none
//
// Return Value: a string containing the fully qualified name
// of a file
//
//************************************************************
string getInputFileName()
{
string f_Name; // fully qualified name of the file
cout << "Please enter the fully qualified name of the " << endl
<< "input text file (i.e. including the path): ";
cin >> f_Name ;
cout << endl; // skip a line
return f_Name;
}
//************************************************************
//
// Function name: getId
//
// Purpose: to prompt the user for the ID
//
//
// Input parameters: char id
//
// Output parameters: none
//
// Return Value: inputId
//
//
//************************************************************
int getId ()
{
int inputId;
cout << " Enter the ID number: " ;
cin >> inputId ;
return inputId;
}
//************************************************************
//
// Function name: Search
//
// Purpose: Locate the ID the user entered. If found displays it with the name if not asks to enter into to the file
//
//
// Input parameters: string id, filehandle passed by reference (ifstream &inFile, ofstream &outFile)
//
// Output parameters: none
//
// Return Value:
//
//
//************************************************************
void search(ofstream &outFile, ifstream &inFile, int ID)
{
int id_num;
string name;
char userreply;
char lookagain = 'Y';
string inputname;
while (!inFile.eof() && (lookagain == 'Y' || lookagain == 'y'))
{
inFile.seekg (0, ios::beg);
inFile.getline(file);
if ( ID == id_num)
{
std::cout << id_num << name;
}
else
{
cout << "Id not found would you like to add it? Y/N " ;
cin >> userreply;
if( userreply == 'Y' || userreply == 'y')
{
cout << " What name would you like to input?" ;
cin >> inputname;
outFile << "\n" << ID << " " << inputname;
outFile.flush();
}
}
cout << "Look for another ID? Y/N " ;
cin >> lookagain;
Hello I am working on a program and have become pretty confused...
I am supposed to write a program that will convert html colours expressed as 6 hexadecimal digits to their individual red, green, and blue components expressed in decimal. If anyone can help me out with some pointers of how to do this then that would be great. Thanks
If you have some DACL permissions on a file, you can use SetFileSecurity() to change the permissions to something else, but what happens when someone deletes all of the DACL? Now you no longer have WRITE_DAC permissions, so you can not modify any discretionary ACE's to it. I have administrative permissions, so how do I restore WRITE_DAC privileges to myself?
Thank you for help :)
Now I am on my way to making a little command prompt program where it types out the alphabet and removes the vowels as a test. BUT, here's the thing, no errors nothing but it doesn't work.
Anyway here is the code if anyone can tell me what is wrong :-/
Code portability basically refers to making source code able to compile on different platform without making any changes in source code.
While coding its very important to keep portability in mind.The best way to introduce code portability is while coding.Keeping certain things into account we can achieve code portability with lesser effort, which we will discuss in this post.There are certain tools too which detect portability problems on source code, its a post processing of code and requires extra effort.
Non-portable code introduces problems like maintenance of different versions, reduces readability, reduces understanding of code etc...
Efforts needs to make legacy or old source code portable, can really make you feel lost in this big programming ocean. So, the best policy is to keep portability into account while writing code, it saves lots of time and efforts on rework. Big question now is - "How to write portable code?".Our source code should be compatible with different environment like different processor, different OS, different version of libraries etc... In this post we would focus on basic tips need to be kept in mind while writing code.
1) Don't assume data type size to be constant across platform, as it may change with platform.
Many a times programmers makes a common mistake by assuming size of pointer and long same.If in some expression sizeof(long) is used, it may give different result on 32-bit and 64-bit OS version. Like if we talk about Microsoft Visual Studio running on 64-bit OS version the pointer size would be 8 byte and size of long comes out to be 4 byte. Program written with such assumption would give false result or may even get crash.So, one has to be very cautious while using data type size across the platform.
2) Don't use specific system constant.
System specific constant should not be used as they are not portable, we are some time not aware of them also. Like system constant "NULL" is specific to windows and will give compilation error on other platform. Instead of "NULL" one can use "0".
3) System file/folder path notation may vary on different platform.
When working with file path one need to be cautious for example "c:\\TestFile.txt" will work on Windows but give error on Linux.For this one i recommend to use forward slash "c://TestFile.txt" , it would work well on both windows and Linux.
4) Avoid using system specific models/libraries.
Don't use system specific models/libraries like Event handling model, Threading libraries, File Creation libraries etc.. . As they are not compatible across platform. Write a wrapper around such models and within wrapper use generic portable libraries. For example, Windows even handling model is totally different from Linux. Windows have special mode for handling events, like we may not find timed wait for multiple object on other platform.
5) Always write default statement in switch case.
Many latest compiler gives compilation error if default is not specified.
6) Always specify return type for functions.
Many latest compiler gives compilation error if return type is not specified.
7) Always specify type with static variables.
Variables declared with static keyword must contain data type with it, some old compiler take int as default type but modern compiler will generate compilation error for it.
8) Always take care of scope of variable.
Like some compiler support variable scope limited to for() while some compiler dont.
For example:-
Don't prefer writing code as below (Non-portable code).
{
for(int i ; ;)
{
//do some thing
}
for(int i ; ;)
{
//do some thing
}
}
Prefer writing code as below (Portable code)
{
for(int i ; ;)
{
//do some thing
}
for(int j ; ;)
{
//do some thing
}
}
9) Don't use C++ commenting style in C code.
Don't use // commenting style in c code, as compile other then microsoft visual studio may generate error for it. Prefer using /* */ commenting style.
10) Take care of include depth for header files and also for file code size.
Microsoft visual studio compiler generated error like "internal compiler error" if include depth is too large or file size exceeds certain limit. Always take care of file size and include depth.
I have tried to cover 10 basic tips for code portability for beginners though there are several other areas too, where we need to focus on advanced portability issues, for e.g. dealing with classes, virtual functions, exception handling, compiler directives, run-time identification. I will cover this topic separately bye for now.
I am having trouble trying to finish this program, What I am suppose to do is make a loop program that should ask the user for the employees number, gross pay, state tax, federal tax, and FICA withholdings. The loop will terminate when 0 is entered for the employee number. After the data is entered, the program should display totals for gross pay, state tax, federal tax, FICA withholdings, and net pay. I can't except any negative number and I can't accept the value of the state, federal, or FICA withholdings to be greater than the gross pay, if it is print the error massage
I know I don't have all of my display totals code in, but what I am having trouble is on the terminating the code if a 0 is entered for the employees number, and I am not suppose to accept any negative number for any of this program. I don't remember how to do it. Can someone please help me out.
# include <iostream>
using namespace std;
int main()
{
int employee;
int gross;
int state;
int federal;
int FICA;
cout << "WEhat is the employees number " << endl;
cin >> employee;
for ( employee = 1; employee >=, employee ++)
cout <<"What is there gross pay" << endl;
cin >> gross;
cout << "What is there state tax " << endl;
cin >> state;
cout << "What is there federtal tax" << encl;
cin >> federal;
cout << "What is there FICA" << endl;
cin >> FICA;
if (state + federal + FICA) > gross;
cout << "YOu are taking to much out of the persons check, please redo" << endl;
cout << " Your employee number is" << employee << endl;
I'm doing a 3d pacman game for a university project which has to be written in c++ (3rd year and having never been taught any c++) My problem is that when I initialise the map array I cannot return the value back to the main method.
The values in the arrays are int's which will be used in constructing the maps (e.g 0 = wall 1 = nothing etc.)
When compiling, the line in the "getCell(x,y)" method gives the error which is "'map' undeclared (first use this function)" and if I put "this->map" it gives an "invalid use of 'this' in non-member function"
Any healp would be greatly appreciated.
My mapInit header:
//Header file for the map initialiser
#ifndef MAPINIT_H_
#define MAPINIT_H_
#include <windows.h> // Header File For Windows
#include <math.h> // Header File For Windows Math Library
#include <stdio.h> // Header File For Standard Input/Output
#include <stdarg.h> // Header File For Variable Argument Routines
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <gl\glaux.h> // Header File For The Glaux Library
//Class mapInit begin
class mapInit
{
public:
unsigned int getCell(unsigned int x, unsigned int y);
void setMap( unsigned int mapSet );
Hi everybody, my name is Candi and I am new here, I was lucky enough to find this forum.
I am new to C++ and am teaching myself because I can't afford school at this time, all I can afford is second hand books :( and I am having a serious problems with this question, and was wondering if any of you could please assist me in writing this and understanding this code pretty please :?:
Just so there is no confusion I am attempting to teach myself C++ through secondhand books, and tutorials, the question I ask comes from a book I have begone to read and thought I was doing rather well, the question stopped me dead in my tracks.
I do not go to school because I can't afford it, due to the recession where I live. I hope hope someone can help me please, I am determined to learn on my own. Can anyone suggest good books e-books and video tutorials as well for a beginner?
Here is my problem maybe someone can help me?
The problem is that I want to write an interactive program in C++ whose input is a series of 6 temperatures from the user of the program. It should write out on file tempdata.dat each temperature as well as the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed for the user via cout.
For example 34.5 38.6 42.4 46.8 51.3 63.1
The file tempdata.dat would contain
34.5
38.6 4.1
42.4 3.8
46.4 4.4
46.8 4.4
51.3 4.5
Hello all,
I am working with a program to calculate the days in a given month. We are to use functions and bool. I have the below code, which worked until I tried to create the function. I continue to get an error about "numberOfDays" not being initialized however if I state that numberOfDays = 0, that is all i get in return, 0....any suggestions?
//C++ program to determin the number of days in a given month
//of a given year.
cout <<"Month and year, and I will calculate the number of days in that month. ";
cout <<endl;
cout <<"Enter the month (eg. 02 for February): ";
cin >> month;
cout <<"Enter the year (eg. 2010): ";
cin >>year;
I am trying to compare 2 vectors to remove any kind of overlap. I have written a simple program but it gives a segmentation fault once I increase / decrease number of vector elements in both.
Is there a better way of doing this. Especially suppose one of the vector is empty or both are empty my program won't work. Can anybody help.
Here is my program:-
#include<iostream>
#include<string>
#include<vector>
using namespace std;
I am using Visual Studio 2008 to debug some code where the goal is create a linked list using pointer variables. Here is the main error I am getting when trying to compile:
error C2227: left of '->Account' must point to class/struct/union/generic type type is 'Link_t'
If I can figure out what it means, I will be able to get like 98% of the code debugged.
At any rate here is my code, any help would be appreciated because linked lists are giving be a great bit of trouble
};// end ListEle_t
//*************************************************************************************************
/* Link Decleration */
//*************************************************************************************************
typedef LLEle_t * Link;
//*************************************************************************************************
/* Class Function Implementations */
//*************************************************************************************************
cAccount::cAccount()
{
strcpy(fname,"");
strcpy(lname,"");
aID=0;
aBal=0;
}// end cAccount::Display
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
int cAccount::compID2ID(cAccount NewAccount)
{
int count;
count=0;
if(this->aID > NewAccount.aID)
{ count=-1;}// end if
else if(this->aID < NewAccount.aID)
{ count=1; }// end else if
else
{ count=0;}//end else
return count;
}// end cAccount::compID2ID
//*************************************************************************************************
/* Function Prototypes */
//*************************************************************************************************
//*************************************************************************************************
/* MAIN */
//*************************************************************************************************
int main()
{
int COUNT=0;
Link_t Start=0;
Link_t Avail=0;
cAccount Account;
Infile_t Infile;
}// end Add
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
void Load(Link_t &Start,Link_t &Avail)
{
Filename_t Filename;
Infile_t Infile;
Link_t Curr=0;
Link_t Pred=0;
cout<<"Program Starting.........."<<endl;
cout<<"Begining Load.........."<<endl<<endl;
cout<<"Enter the name of the data file to be used:"<<endl;
cin>>Filename;
Infile.open(Filename,ios::in);
cAccount NewAccount;
NewAccount.Read(Infile);
while(!Infile.eof())
{
Add(Avail,Start,NewAccount);
NewAccount.Read(Infile);
};// end Print
//*************************************************************************************************
/* END OF SOURCE CODE */
//*************************************************************************************************
I'm working on a structure program that has an array (m) that asks the user to enter its values, and then it transfers the even numbers to an array (even) and the odd to another (odd). Both (evan) and (odd) arays are in a structure (x) ; plus, I have made another structure (y) that is connected to (x) and has it same attributes.
My problem is, that after I run the program and add the numbers, I don't get the values in the (odd) and (even) arrays ; but instead I get their memory addresses I guess!
Plus in the (cout) area at the end of the program, I wanna add more cool things that displays higher/lower numbers in both arrays, and also the total count/sum of both arrays, so the program will display these things after adding the values by the user:
- Even numbers are: ------------
- Odd numbers are: -------------
- Higher even number: ---------
- Lower even number: ----------
- Higher odd number: -----------
- Lower odd number: -----------
- The sum of even numbers: -------
- The sum of odd numbers: --------
Currently I'm using the way posted below which works but it sure isn't elegant. Can anyone think of a way to test if the UI has loaded without using system() or popen() in c++
Hello i was wondering how to store a tridiagonal matrix in c++
i know i have to use three arrays for the upper lower and diagonal terms, but how do i then use parenthesis operator to access single elements of the matrix when it is stored as three separate arrays....also how would i code a tridiagonal matrix multliplication with a vector?
template<bool b> class B
{
friend void foo<b>(void);
};
template<bool b>
void foo(void){};
everything works just fine.
But when I incapsulate all this in another class, I receive errors:
struct C
{
template<bool b> void foo(void);
template<bool b> class B
{
friend void C::foo<b>(void);
};
};
template<bool b>
void C::foo(void){};
.
In Visual C++ 2008 I get these errors:
error C2975: 'b' : invalid template argument for 'C::foo', expected compile-time constant expression;
error C2245: non-existent member function 'C::foo' specified as friend (member function signature does not match any overload).
In a C++ function
How to check if the minimum and maximum values of an array are not equal and the minimum and maximum values of the array are not adjacent to one another.
Also the minimum value occurs exactly once in the array and the maximum value occurs exactly once in the array.
I seem to be having a relatively small problem with a Maze program I'm working on. Basically, I read a txt file containing a maze into a 12 x 12 2D array, but the problem is when I try to display it, none of the white spaces that are in the maze show up. I know it has something to do with the getline() function, but I have no clue as to where to put it.
Here is what an example of a txt file used contains:
I've a case where the parameter to be passed to the macro function is not known till the point it is called.
example: (continuing the example quoted below)
- number "12" passed to the " DEFINE_FUNC( n )" macro is determined at the time of execution.
I cannot pass a string/int var from the macro
(i.e. i cannot use
int num = 12;
DEFINE_NUM(num);
)
Can you please help me and share any solution for such situation?
Thanks in advance!
Aditya
Quote:
Originally Posted by Duoas (Post 539703)
Actually, it is possible. You need to use token concatenation. #define DEFINE_FUNC( n ) void func_ ## n()
You would use it in the normal way: DEFINE_FUNC( 12 );
The preprocessor would turn that into: void func_12();
While I can't imagine why you want to do this, there are, in fact, legitimate reasons to do token concatenation (which goes a long way into explaining why the preprocessor can do it at all).
I did search around and there are few examples about this situation (not much as I would have expected though), but I want to know the procedure or how to find the solution.
Basically I have a 32-bit UNSIGNED register. I want to know how to calculate the value when I subtract 1 when the value is zero (all zero bits).
Any reference to a tutorial about this specific case or explanation is appreciated.
Can someone please advise me as to why my assignment is not working? I am doing the exact same thing I did on another assignment and for some reason it wont work.
Assignment
1. You are a programmer that works for a local bank. You are creating classes to be used in the class library for this bank for all of its programs. You will also create a main() to test your new classes.
Talking to the bank manager you find out that your bank keeps track of Accounts and that there are more than one type of Account. There are CheckingAccounts, SavingsAccounts, and CreditCardAccounts.
(Credit card accounts are actually called line of credit accounts in the real world. But, let’s call them this here to make it clearer.)
You learn that all of the accounts are often grouped together and treated the same in many reports. So, they all need to inherit from the account class.
Account Class:
Attributes/data members
number (an integer)
balance (a double)
rate (a double)
Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest()
Note: The ApplyInterest() function needs to be a virtual function. It is going to be overridden in the subclasses.
Constructor(s):
This class must have a constructor that accepts all of the data to create an Account and initializes its data members.
Validation in member functions/ Business Rules:
1) Rates should be between .01 and .18 (it is an interest rate as a decimal)
2) Balances should never be allowed to be set to a negative value.
CheckingAccount Class:
This class inherits from the Account class
Attributes/data members
checknumber (an integer) [representing the last check number written/processed.]
pin (an integer)
Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “2.35 has been added to checking”
Constructor(s):
This class must have a constructor that accepts all of the data to create a CheckingAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)
SavingsAccount Class:
This class inherits from the Account class
Attributes/data members
Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “5.01 has been added to savings”
Constructor(s):
This class must have a constructor that accepts all of the data to create a SavingsAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)
CreditCardAccount Class:
This class inherits from the Account class
Attributes/data members
cardnumber (a string)
Behaviors/member functions:
1) accessor (get) and mutator (set) functions for all attributes.
2) ApplyInterest(), this function should take the balance and multiply it by the rate to find the interest this period…then add it to the existing balance. Print a message to the user with the amount in this format “5.23 interest has been charged to this credit card on its unpaid balance”
Constructor(s):
This class must have a constructor that accepts all of the data to create a CreditCardAccount and initializes its data members. (This includes all of the data it needs to pass to the Account class constructor or set directly for the account class from this constructor.)
Main()
1) In main for this program create a checking account, savings account, and credit card account for a customer with test data as follows and place them in an array:
2) Print out all of the data for the accounts for the user.
3) Use a loop and call the ApplyInterest() method to add interest to the balance and print appropriate messages to the user.
4) Print out all of the data for the accounts for the user.
Can someone break down what this array loop means exactly? Mathematically I can't make any sense of it. I've reread this section of my book multiple times, but it's not sinking in.
int alpha[a];
int j;
for(j = 0; j< 5; j++)
{
alpha[j] = 2 * j;
if(j % 2 == 1)
alpha[j - 1] + j;
}
I'm new to C++ ; this was quiz question I missed. The correct answer was alpha = {3, 2, 9, 6, 8} - just not sure how/why! TY.
Your third assignment is to write a C++ program that will print out the primes numbers between 2 and 100. However, you must use two functions in your program.
The first function, factor, takes an int, n, and returns two factors of n whose product is n. For example, if n is 36, factor could return 6 and 6 (or 2 and 18, or 4 and 9, ...). If n is prime, factor should return 1 and n (in that order). If n is not prime, factor should not return 1 and n, but find two non-trivial factors. The factor function should have a return type of void and use call-by-reference parameters to return the two factors.
The second function, prime, should return a Boolean value - true if the argument is prime, and false if it is not prime. Since a good programmer is lazy, the prime function should call the factor function instead of doing any work itself.
Finally, the main program should loop through all the numbers between 2 and 100, and print out just those that are prime. The main program should call the prime function appropriately, which in turn calls the factor function.
_____________________________________________
I think I'll be able to figure out how to find the prime numbers, but I have no clue how to find factors of a number
I've run into linking problems before, so I thought I had them figured out. This one I'm using every tool I have, but I can't seem to identify what the issue is.
Did a build from the yaml site yesterday, I keep getting this linking error at runtime. I set LD_LIBRARY_PATH, but as you can see the shared object that is missing with ldd is in the path. Am I missing something here?
$ g++ -fPIC -Wall -lyaml-cpp main.c -L$YAMLCPP/yaml-cpp/build-I$YAMLCPP/yaml-cpp/include
$ a.out
a.out: error while loading shared libraries: libyaml-cpp.so.0.2: cannot open shared object file: No such file or directory
$ ldd a.out
libyaml-cpp.so.0.2 => not found
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00000034ce400000)
libm.so.6 => /lib64/tls/libm.so.6 (0x00000034cbe00000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00000034ce200000)
libc.so.6 => /lib64/tls/libc.so.6 (0x00000034cbb00000)
/lib64/ld-linux-x86-64.so.2 (0x00000034cb700000)
$ ls $LD_LIBRARY_PATH
CMakeCache.txt CTestTestfile.cmake libyaml-cpp.so.0.2.4 yaml-cpp.pc
CMakeFiles libyaml-cpp.so Makefile yaml-reader
cmake_install.cmake libyaml-cpp.so.0.2 util
This is a non technical question, I am not a programmer, but I have a question on creating a C++ program, I hope somone could answer for me, and to see if this could be done in C++, so I could hire someone to make this for me.
I am using a program called gpsmapedit, would it be possible to make a program in C++ that will automatically run certain functions of gpsmapedit, while I am gone during the day?
Any help would be greatly appreciated.
Thank you,
Dave
i need help with my assignment...i'm so new with this c++ programming...i only know how to do up to division only for this question... and for question two,i really have no idea how to start...can someone help me out and try to make me understand how the code will works...i really need some help...
QUESTION 1
Write a calculator program that allows the user to select which operation they would like to perform such as:
•Addition
•Subtraction
•Multiplication
•Division
•Modulus
•Square (x2)
•Square root ( )
•Convert Celsius to Fahrenheit (Fahrenheit = 1.8 Celsius +32)
•Convert Celsius to Kelvin (add 273.15 °)
•Convert Fahrenheit to Celsius (Celsius = (F-32) x (5/9))
•Convert Fahrenheit to Kelvin (Kelvin = 5/9 x (Fahrenheit - 32) + 273)
Make sure your program contains menu and will keep on looping until the user enter a specific value to end it. Please use Functions to do the calculation. You might want to use switch for the menu.
Question 2
A parking garage charges a RM2.00 minimum fee to park for up to three hours. The garage charges an additional RM0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24 hour period is RM10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of 3 customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday’s receipts. The program should use FUNCTION to determine the charge for each customer.
Hey guys, I need a little help. I'm writing a palindrome checker for fun, and I need to ignore/delete spaces and punctuation. I compare my two strings using strcmp and I use pointers to go through the first part of the program. I'm now stuck trying to factor out the spaces and punctuation, and I'm guessing I will have to do something b4 the strcmp is called. What should I do to delete all the spaces and punctuation?
my problem is that it sends and receives the file but only if i stop the program,if not it just remains stuck in the while loop in receive() function ....why is that ?
I downloaded a dll for head tracking, and have been trying to use it for some time now. I am trying to make a python script that uses it and am getting errors. This is the post.
I posted it in the python forums, and no replies yet, since this deals with C++ I figured I would post in here to looking for some help.
I was working on the being of a cash register and I was testing this portion of my code. It compiles, but when I input my first items name I get a windows error and the program ends. I would appreciate any help an/or explanation.
#include <iostream> // allows output and input
#include <iomanip> //allows i/o manipulation
#include <stdlib.h>
#include <fstream> // allows file i/o
#include <string> // allows the use of strings
//declares variables
int current_input_number;
int number_of_items;
main()
{
using namespace std;
system("COLOR 0a"); // changes color
//declares an array of strings
string item_name[number_of_items];
cout << "How many items does the customer have? \n";
cin >> number_of_items;
for (current_input_number = 1; current_input_number < number_of_items; current_input_number++)
{
cout << "Please enter product number " << current_input_number << '\n';
cin >> item_name[current_input_number];
hey,
to start with heres the backdrop;
me and a friend from school have a year to create a fully working web browser and for this i think C++ would be best.
heres where i need help, i have no experience with C++ and i need to learn it from near-scratch.
so what steps should i take and how should i start it?
should i sit and learn C++ first or learn as i progress?
what programs should i use as a compiler and to write the code?
what engine should i use?
how do i incorporate all this into a program?
what other advice can you give?
Does anyone know of any classes that process string mathmatical equations ? E.g. 2+2(6*5(2-1)) - It is specified on the command line and stored as a string.
Hello everyone,
I'm currently in college for Game programming and I'm coming in having known nothing about programming at all. I'm currently learning Object Orientated C++ Programming. I have been at this one problem for two weeks and I'm completely stumped. I currently have three files the main cpp file, the cpp file with all the information, and then the header file. I'm completely stuck on how to properly call the functions into main here are the following codes. This is just the first of many problems I am working on. All help is highly Appreciated as I'm trying to do this as I've gotten little help from my professor. Whom I believe thinks I should figure this out on my own. But with time restraints, it is exceedingly difficult and I fully intend on graduating and getting into the industry. Again thank you ahead of time for any help in helping me fix this and any future questions.
header:
#define Asteroids_h
class Asteroid
{
private:
int astSpeed;
int astSize;
Asteroid () {}
public:
void displayStats(int AsteroidNumber);
void setSize( int astSize);
void setSpeed(int astSpeed);
int setSpeed()
{
return astSpeed;
}
int setSize()
{
return astSpeed;
}
};
core file:
#include <iostream>
using namespace std;
class Asteroid
{
int astSize;
int astSpeed;
int AsteroidNumber;
public:
Asteroid ( int Size, int Speed, int AsteroidNumber )
{
setSpeed( Size);
setSize (Speed);
}
int getSize()
{
return astSize;
}
int getSpeed()
{
return astSpeed;
}
the current error(s) I have thus far is the following:
asteroidproject\asteroidmain.cpp(9) : error C2664: 'Asteroid::Asteroid(const Asteroid &)' : cannot convert parameter 1 from 'int' to 'const Asteroid &'
1> Reason: cannot convert from 'int' to 'const Asteroid'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
1>e:\cit43\asteroidproject\asteroidmain.cpp(10) : error C2664: 'Asteroid::Asteroid(const Asteroid &)' : cannot convert parameter 1 from 'int' to 'const Asteroid &'
1> Reason: cannot convert from 'int' to 'const Asteroid'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
I have been doing TC++ programing for the last 2 years.. This evening all of a sudden I made the switch to vc++.. here is the code.. my first ever Visual C++ programme.. it is compiling without errors but the console window poped and disappeared quickly.. what is wrong? something similar to getch() missing or what?
// test2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout<< "Hello world";
return 0;
}
hello , I am making a small game engine and I have 2 header files engine.h and objects.h they both include each other. However it seems that its not getting included into objects.h , what is the "right" way to fix this ?
sorry , I'm too lazy to gut out my code to make it more readable
//Render text
enum textquality { solid, shaded, blended };
SDL_Surface * drip_draw_text(TTF_Font *fonttodraw, string texts, int fgR, int fgG, int fgB,int fgA , int bgR, int bgG, int bgB, int bgA, textquality quality);
// Load
unsigned int drip_load_font(string file, int ptsize);
unsigned int drip_load_image(string file);
unsigned drip_load_music(string file);
unsigned drip_load_sound(string file);
// Get
SDL_Surface * drip_get_image(unsigned int img_num);
I am a C programmer. I am working on a C++ code and translating it into C.
I got stuck in a point where I do not understand what is going on.
I would kindly ask if you would mine help me to understand these problems.
I have three problems:
1)There are two arrays with different length:
vector<double> D;
double temp[5];
//and then:
D.resize(3, temp);
Does the programmer wants to copy temp[0], temp[1], and temp[2] into D[0], D[1], and D[2] ?
2)There is a two dimensional array
vector<vector<double> > F;
it is initialized like this:
F.resize(3, temp);
Since temp[5] is a one dimensional array, is it possible to copy it into a two dimensional array?
Finally array F which is a two dimensional array is passed as a one dimensional array into a function like this:
//declaration of function
void do(vector<double> & F);
main(){
// now F which is sopposed to be a two dimensional array is used like
for(int I; i<3; i++) do(F[i]); // !!!!!!!!!!!!!
}
In C it is not possible as far as my knowledge. Is this possible in C++?
Hi,
I'm reading from a text file and writing to another one.My problem is that the data is being written to the new file as one line..i.e., when the end of a line is reached it does not start writing a new line but continues on the same line.. Can someone please tell me how to make it write data line by line? this is my code..Any improvements and suggestions will be appreciated. Thanks
Hi, I have this homework problem that I need some help on:
In 3D: Given 2 links attached end to end with lengths L0 and L1 respectively, a point P0 that the first link starts at, and a point P1 that you want the end of the 2nd link to be at, write a function that finds the configurations of the links that put the 2nd link’s end at point P1.
I feel like I'm missing something because I don' t know where to start with it. I really don't even know what the problem is asking for. I'm hoping one of you comp. sci. or math geniuses will be able to help. Any tips/help would be appreciated.
i want to give a presention on functions use in code and want to give a comparision by function call by value and by reference with different cods can any one help me ,as give me these codes?
I am converting a console IO program to a file IO program. The program worked perfectly as a console IO. I thought I made the appropriate changes to the program. It compiles, and when I run it output does go to my output text file, but the output is the same as if the input text file was blank. No matter what I do to the input text file the output text file is the same, so somehow my program is not reading it. I know that I spelled the input file name correctly when opening it in the program. Here is the program, thanks for any suggestions.
#include <fstream>
using std::ifstream;
using std::ofstream;
using std::endl;
int main()
{
ifstream inStream;
ofstream outStream;
outStream << "Please enter the average rainfall (to the nearest inch), starting with January, " << endl;
outStream << "then February, then March, etc. Make sure to press enter after every month." << endl;
for (x = 0; x < 12; x++) // x used to take exactly 12 inputs
{
inStream >> avgRain[x];
outStream << endl;
}
outStream << "What is numeral of the current month? (Jan is 1, Oct is 10, etc)" << endl << endl;
inStream >> y;
outStream << endl;
if (y > 1) // This converts y to variable z. z accounts for the array going from 0 - 11
z = (y - 2);// rather than 1 - 12 and represents the previous month number in the array currentRain
else if (y == 1)
z = 11;
else
z = 10;
outStream << "Please enter the amount of rain (to the nearest inch) that fell " << endl;
outStream << "last month. Then enter the amount that fell the month before " << endl;
outStream << "that. Continue until you have entered an amount for the last 12 " << endl;
outStream << "months. Press enter after every measurement." << endl;
int m = 0;
while (m < 12) // m is used to make sure the while statement is executed exactly 12 times
{
if (z > 0)
{
inStream >> r; // r is the last recorded rain measurement for any month z
outStream << endl;
currentRain[z] = r;
z--;
}
else
{
inStream >> r;
outStream << endl;
currentRain[0] = r;
z = 11;
}
m++;
}
char results = 'g'; // results is the variable that determines how the data is represented
outStream << endl; // and it is initialized to g (graph)
while ((results == 'g') || (results == 'G') || (results == 'c') || (results == 'C'))
{
outStream << "Enter g to see the results graphically or c to see a chart. Or press any " << endl;
outStream << "other key to quit." << endl << endl << endl;
inStream >> results;
if ((results == 'c') || (results == 'C'))
{
outStream << "Month__Average Rainfall__Previous Recorded Rainfall__PRF Deviation From Average" << endl;
int g = avgRain[x]; // g is initialized to the value of any given x index in
while (g > 0) // the avgRain array
{
outStream << "*";
g--;
}
outStream << endl;
outStream << (x + 1) << " ";
int h = currentRain[x]; // h is similar to g except used for the currentRain array
while (h > 0)
{
outStream << "*";
h--;
}
outStream << endl << endl;
x++;
}
outStream << "The top line indicates the average rainfall; bottom indicates the last " << endl;
outStream << "recorded measure for that month. Every * represents 1 inch." << endl << endl << endl;
}
}
inStream.close();
outStream.close();
}
2008 scandalz.net
Oh, I am a C programmer and I'm okay
I muck with indices and structs all day
And when it works, I shout hoo-ray
Oh, I am a C programmer and I'm okay