Obviously, this type of constructor would allow the transfer of the resource, since the source object can be modified and put into an empty-state (or "zombie-state"). But there are two problems with the above, which make it an impractical solution. First, a temporary object, formally referred to as anrvalue, cannot be bound to a non-const reference, meaning that this constructor will not be able to move resources from a temporary object to the newly constructed object."
I have a question here: Isn't the compiler-generated copy constructor called if I used an rvalue like int_vector(int_vector(5)) and it gets a shallow copy of the temporary object just like the move constructor?
AVIStreamGetFrameOpen is always returning NULL. I checked to see if I could open the AVI file in windows media player and that worked, so that means it can't be a codec problem, right? I'm not too sure. All the variables have valid values before the call to AVIStreamGetFrameOpen
string operand;
string opCode;
struct MacroNameTable{
string macroName;
int start;
int end;
int invocation;
string operandCounter;
};
struct MacroNameTable NAMTAB[NAMSize];
void addNAMTab(){
NAMcounter++;
cout <<"check NAMcounter: ["<<NAMcounter<<"]"<<endl;//debug
cout <<"check this operand: ["<<operand<<"]"<<endl;//debug
cout <<"check this opCode: ["<<opCode<<"]"<<endl;//debug
NAMTAB[NAMcounter].macroName=opCode;
NAMTAB[NAMcounter].start=DEFcounter;
NAMTAB[NAMcounter].operandCounter="AA";
}
operand and opCode will read from text file. As you can see from the snapshot, after read from file,
current operand="&INDEV, &BUFADR, &RECLTH"
current opCode="RDBUFF"
this line cause a problem , it gives me runTime error
why ?? I've debug whole day long and I still cannot solve this, it supposed to be working because opCode is string , so does NAMTAB[NAMcounter].macroName
hi, i just started learing 2d game programming. so far i can make my character go right, left and check for collisions. But i cant find out how to make him jump. any thing will be helpfull.
so this program is really simply. my player(ch1,bmp) just move right and left. on my map there are wall and coin. if player hit a wall it should stop. but if it hit a coin, coin should get delete.
problem iam having is that for some reason player(ch.bmp) is display as a coin.
i think its bc iam not using sprite right.
#include "DarkGDK.h"
void DarkGDK (void)
{
dbSyncOn(); // dbSyncOn() = turn sync on, this means we control when the screen is updated
dbSyncRate(60); //maximum frame rate will be set at 60 frames per second
dbDisableEscapeKey(); // to exit from main while loop and stop the game
dbSetImageColorKey(255,255,255); //igore color
dbLoadImage("ch1.bmp",1); //load image to memory
dbLoadImage("wall.bmp",2);
dbLoadImage("coin.bmp",3);
dbSprite(1,100,50,1); //mage#,x,y,image# -display image
dbSprite(1,400,50,2);
dbSprite(1,250,50,3);
// keep looping through until user enter escape key
while (LoopGDK())
{
//move image forward
if(dbRightKey() == 1)
{
dbRotateSprite(1, 90); //rotate image
dbMoveSprite(1,1); //image#, move one space up
dbRotateSprite(1,0); //rotate back to normal
if(dbSpriteCollision(1,3) == 1) //del coin
{
dbDeleteSprite(3);
}
if(dbSpriteCollision(1, 2) == 1)
{
dbRotateSprite(1, 270); //rotate image
dbMoveSprite(1,1); //image#, move one space up
dbRotateSprite(1,0); //rotate back to normal
}
}
//move image left
if(dbLeftKey() == 1)
{
dbRotateSprite(1, 270); //roate image
dbMoveSprite(1,1); //image#, move one space up
dbRotateSprite(1,0); //rotate back to normal
if(dbSpriteCollision(1,3) == 1) //del coin
{
dbDeleteSprite(3);
}
if(dbSpriteCollision(1, 2) == 1)
{
dbRotateSprite(1, 90); //rotate image
dbMoveSprite(1,1); //image#, move one space up
dbRotateSprite(1,0); //rotate back to normal
}
}
if (dbEscapeKey() == 1) //if the ecape key is pressed, the program will exit
{
break;
}
dbSync(); //update the screen
}//end of main while loop
for(int i = 1; i < 10; i++)
{
dbDeleteImage(i); //delete
dbDeleteSprite(i); //delete
}
return;
}
'Server.exe': Loaded 'C:\Users\User\Desktop\Server\Debug\Server.exe', Symbols loaded.
'Server.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\ws2_32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msvcrt.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\sechost.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\nsi.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded.
'Server.exe': Loaded 'C:\Windows\SysWOW64\mswsock.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\user32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\gdi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\lpk.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\usp10.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\advapi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\datamngr.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\wtsapi32.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\dbghelp.dll', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\datamngr.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\dbghelp.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\wtsapi32.dll'
'Server.exe': Loaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\IEBHO.dll', Cannot find or open the PDB file
'Server.exe': Loaded 'C:\Windows\SysWOW64\dbghelp.dll', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Program Files (x86)\Searchqu Toolbar\Datamngr\IEBHO.dll'
'Server.exe': Unloaded 'C:\Windows\SysWOW64\dbghelp.dll'
'Server.exe': Loaded 'C:\Windows\SysWOW64\WSHTCPIP.DLL', Cannot find or open the PDB file
'Server.exe': Unloaded 'C:\Windows\SysWOW64\WSHTCPIP.DLL'
Hi,
I've just finished my c++ class (mechanical engineering) and as the final exam we have to create a simple program with graphical user interface and I need some help from you guys.
The task is this: we have to make a simple GUI that can take the diameters of a Shaft/Hole and calculate how they fit together (pressed, smooth fit...).
Now the problem: i could write the code in c++ but i don't know how to create the buttons or the user interface and how to connect the code with those buttons.
I'm using Visual Studio 2010 professional.
P.S Don't get me wrong i'm not asking you to do my work, just some suggestions on where to start or maybe some tutorials or something like that.
Thank you.
P.S If this is the wrong place for this thread feel free to move it or tell me i' ll remove it.
Hello, im a bit new to c++ and learning in my own, but im stuck to a problem.
Im trying to do a practice converting string/c-string to int :
Sum of Digits in a String
Write a program that asks the user to enter a series of single digit numbers with nothing
separating them. Read the input as a C-string or a string object. The program
should display the sum of all the single-digit numbers in the string. For example, if the
user enters 2514, the program should display 12, which is the sum of 2, 5, 1, and 4.
so i make a simple program first like this :
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
const int size = 5;
char array[size];
int acc = 0;//for accumulator
int number[5];
for(int count = 0; count < size; count++)
{
cout<<"enter a number = ";
cin>>array[count];
number[count] = atoi(array[count]);
acc += 0;
}
cout<<endl<<"the total number = "<<acc;
return 0;
}
but theres problem in 'atoi' to convert the string, the compiler says = 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
anyone can help me?
Hello. I am working on a windows form right now. My form is very full and i am using many textures. I have double buffered my form and made exteded classes for anything with a texture that has double buffering. Before i had double buffered everything my form was very jerky when i moved it offscreen. It would kinda stick and jerk. I notice this happens only when i move it offscreen. I have not found any information on this anywhere, im surprized im the only one who has experiences this. Another thing i have thaught of is drawing and offscreen image of my form, but i do not know how to do that . Thans all for any advice i cant continue on my project until this has been resolved thanks.
In my project (Borland C++ Builder, Windows Xp ) am using following code for opening the file
TOpenDialog *OpenDialog;
OpenDialog->Filter = "all files (*.*)";
OpenDialog->InitialDir="::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
OpenDialog->Execute();
But the "My computer" tab is empty its not showing the drives. Rest "My Rescent Documnets" , "Desktop", "My Documents", "My network drives" all are showing the folders or drives in them.
I had created a new project in BCB with the same above code in that its working fine. When i am including this new project files in my old project again the error is reproducable.
I tried to use OpenFileDialog the code as follows :-
OpenFileDialog *OpenFileDialog1 = new OpenFileDialog;
OpenFileDialog1->Filter = "all files (*.*)";
OpenFileDialog1->InitialDir="::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
OpenFileDialog1->Execute();
this is giving compliation error : Undefined symbol 'OpenFileDialog'
Help me out to figure out the problem
I have this C++ network client program but it has an error.
Here is the error:
error C2664: 'wsprintfW' : cannot convert parameter 1 from 'char [128]' to 'LPWSTR'
Here is the code:
// Client program example
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEFAULT_PORT 2007
// TCP socket type
#define DEFAULT_PROTO SOCK_STREAM
void Usage(char *progname)
{
fprintf(stderr,"Usage: %s -p [protocol] -n [server name/IP] -e [port_num] -l [iterations]\n", progname);
fprintf(stderr,"Where:\n\tprotocol is one of TCP or UDP\n");
fprintf(stderr,"\t- server is the IP address or name of server\n");
fprintf(stderr,"\t- port_num is the port to listen on\n");
fprintf(stderr,"\t- iterations is the number of loops to execute.\n");
fprintf(stderr,"\t- (-l by itself makes client run in an infinite loop,\n");
fprintf(stderr,"\t- Hit Ctrl-C to terminate it)\n");
fprintf(stderr,"\t- The defaults are TCP , localhost and 2007\n");
WSACleanup();
exit(1);
}
int main(int argc, char **argv)
{
char Buffer[128];
// default to localhost
char *server_name= "localhost";
unsigned short port = DEFAULT_PORT;
int retval, loopflag = 0;
int i, loopcount, maxloop=-1;
unsigned int addr;
int socket_type = DEFAULT_PROTO;
struct sockaddr_in server;
struct hostent *hp;
WSADATA wsaData;
SOCKET conn_socket;
if (argc >1)
{
for(i=1; i<argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch(tolower(argv[i][1]))
{
case 'p':
if (!stricmp(argv[i+1], "TCP"))
socket_type = SOCK_STREAM;
else if (!stricmp(argv[i+1], "UDP"))
socket_type = SOCK_DGRAM;
else
Usage(argv[0]);
i++;
break;
case 'n':
server_name = argv[++i];
break;
case 'e':
port = atoi(argv[++i]);
break;
case 'l':
loopflag =1;
if (argv[i+1]) {
if (argv[i+1][0] != '-')
maxloop = atoi(argv[i+1]);
}
else
maxloop = -1;
i++;
break;
default:
Usage(argv[0]);
break;
}
}
else
Usage(argv[0]);
}
}
if ((retval = WSAStartup(0x202, &wsaData)) != 0)
{
fprintf(stderr,"Client: WSAStartup() failed with error %d\n", retval);
WSACleanup();
return -1;
}
else
printf("Client: WSAStartup() is OK.\n");
if (port == 0)
{
Usage(argv[0]);
}
// Attempt to detect if we should call gethostbyname() or gethostbyaddr()
if (isalpha(server_name[0]))
{ // server address is a name
hp = gethostbyname(server_name);
}
else
{ // Convert nnn.nnn address to a usable one
addr = inet_addr(server_name);
hp = gethostbyaddr((char *)&addr, 4, AF_INET);
}
if (hp == NULL )
{
fprintf(stderr,"Client: Cannot resolve address \"%s\": Error %d\n", server_name, WSAGetLastError());
WSACleanup();
exit(1);
}
else
printf("Client: gethostbyaddr() is OK.\n");
// Copy the resolved information into the sockaddr_in structure
memset(&server, 0, sizeof(server));
memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */
if (conn_socket <0 )
{
fprintf(stderr,"Client: Error Opening socket: Error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Client: socket() is OK.\n");
// Notice that nothing in this code is specific to whether we
// are using UDP or TCP.
// We achieve this by using a simple trick.
// When connect() is called on a datagram socket, it does not
// actually establish the connection as a stream (TCP) socket
// would. Instead, TCP/IP establishes the remote half of the
// (LocalIPAddress, LocalPort, RemoteIP, RemotePort) mapping.
// This enables us to use send() and recv() on datagram sockets,
// instead of recvfrom() and sendto()
printf("Client: Client connecting to: %s.\n", hp->h_name);
if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
fprintf(stderr,"Client: connect() failed: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Client: connect() is OK.\n");
// Test sending some string
loopcount = 0;
while(1)
{
wsprintf(Buffer,"This is a test message from client #%d", loopcount++);
retval = send(conn_socket, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR)
{
fprintf(stderr,"Client: send() failed: error %d.\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("Client: send() is OK.\n");
printf("Client: Sent data \"%s\"\n", Buffer);
retval = recv(conn_socket, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR)
{
fprintf(stderr,"Client: recv() failed: error %d.\n", WSAGetLastError());
closesocket(conn_socket);
WSACleanup();
return -1;
}
else
printf("Client: recv() is OK.\n");
// We are not likely to see this with UDP, since there is no
// 'connection' established.
if (retval == 0)
{
printf("Client: Server closed connection.\n");
closesocket(conn_socket);
WSACleanup();
return -1;
}
printf("Client: Received %d bytes, data \"%s\" from server.\n", retval, Buffer);
if (!loopflag)
{
printf("Client: Terminating connection...\n");
break;
}
else
{
if ((loopcount >= maxloop) && (maxloop >0))
break;
}
}
closesocket(conn_socket);
WSACleanup();
return 0;
}
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 222 1 winapi_1
Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 5940 1 winapi_1
Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\program files\microsoft sdks\windows\v5.0\include\winnt.h 5940 1 winapi_1
Why do i have to include stdafx.h everytime in visual C++ 2010 express. Evertime i make a project i have to include that damn header, whats so special about it and how can i avoid including it and still compile my program. I have tried to leave it out but it doesnt want to compile then givving an arror about forgetting to include stdafx.h.
And if you know how to compile a single source file without having to create a new project i will epreciate it.
I am using Visual Studio C++ express 2010
Oh and if you know where to get a good tutorial about making a simple server-client side TCP chat program in C++ with winsock2.h
Hi ive made a code where a user makes a list and then displays it. he may also delete objects one by one.
suppose i wished to clear all in one go. How would i go about doing this? thank you in advance. my code is below. all works except the clear all option does nothing.
#include <iostream>
using namespace std;
struct node {
string pro[10];
string product;
node *link;
};
node* buildListForward()
{
node *first,*newNode, *last;
string num;
cout<<"\nEnter Products\nEnter 'quit' when done\n";
cin >>num;
first=NULL;
while(num!="quit")
{
newNode = new node;
newNode->product =num;
newNode->link = NULL;
if(first==NULL)
{
first = newNode;
last= newNode;
}
else
{
last->link = newNode;
last = newNode;
}
cin>>num;
}
return first;
}
node* deleteNode(node *head,string delItem)
{
node *current,*prev;
bool found=false;
current = head;
prev = head;
while(current!=NULL && !found) {
if(current->product==delItem) found = true;
else {
prev = current;
current = current->link;
}
}
if(found) {
if (current==head) head = current->link;
else
prev->link = current->link;
delete current;
}
return head;
}
int main() {
node *head, *current;
string num;
int pos;
int menu;
bool quit=false;
do{
cout<<"1.....Build List"<<endl;
cout<<"2.....Delete Item"<<endl;
cout<<"3.....Display"<<endl;
cout<<"4.....Logout"<<endl;
cout<<"5.....Quit"<<endl;
cout << "Enter choice: ";
cin >> menu;
switch(menu){
case 1:cout<< "\nBuild List"<<endl;
head = buildListForward();
system("cls");
break;
case 2:cout<< "\nDelete Item"<<endl;
cout<<"Enter number to delete\n";
cin>>num;
head = deleteNode(head,num);
system("cls");
break;
case 3:cout<< "\nDisplay Item"<<endl;
current = head;
while(current!=NULL) {
cout<<current->product<<endl;
current = current->link;
}
system("pause");
system("cls");
break;
case 4:cout<<"Clear All";
system("cls");
break;
case 5:quit=true;
break;
default:cout<<"Invalid entry must be 1..5"<<endl;
}
}while(!quit);
system("pause");
return 0;
}
Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp
Here is log_header.h
#include<fstream>
#include<iostream>
using namespace std;
class thrower{
fstream myfile2;
public:
void errormessage();
};
void thrower::errormessage(){
cout<<"Thrower works\n";
///////These are log commnands////////
myfile2.open("C:\\error2.txt",ios::out);
myfile2<<"Message 2\n"<<endl;
myfile2.close();
////////////////////////////////////////
};
Here is log_test.cpp
#include"log_header.h"
#include<fstream>
#include<iostream>
using namespace std;
thrower t;
int main(){
fstream myfile;
try{
int y=4;
if (y<5){
throw t;
}
}
catch(thrower tt){
tt.errormessage();
myfile.open("C:\\error.txt",ios::out);
myfile<<"Message \n"<<endl;
myfile.close();
}
return 0;
}
If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.
Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp
Here is log_header.h
#include<fstream>
#include<iostream>
using namespace std;
class thrower{
//fstream myfile2;
public:
void errormessage();
};
void thrower::errormessage(){
cout<<"Thrower works\n";
///////These are log commnands////////
//myfile2.open("C:\\error2.txt",ios::out);
//myfile2<<"Message 2\n"<<endl;
//myfile2.close();
////////////////////////////////////////
};
Here is log_test.cpp
#include"log_header.h"
#include<fstream>
#include<iostream>
using namespace std;
thrower t;
int main(){
fstream myfile;
try{
int y=4;
if (y<5){
throw t;
}
}
catch(thrower tt){
tt.errormessage();
myfile.open("C:\\error.txt",ios::out);
myfile<<"Message \n"<<endl;
myfile.close();
}
return 0;
}
If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.
#include <Stdafx.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int rand_0toN1(int n);
int main()
{
int n, i;
int r;
srand(time(NULL)); // set a seed for random-number generation.
cout<< "Enter number of dice to roll: ";
cin>> n;
for(i = 1; i <= n; i++)
{
r = rand_0toN1(6) + 1;
cout<< r << " ";
}
system("pause");
return 0;
}
// random 0 to n1 function
int rand_0toN1(int n)
{
return rand() % n;
}
I'M having trouble understanding a few lines of this program, the first one is srand(time(NULL));
I'M assuming srand is the function so what is time in this code. Also, if this line is generating a random number where is it storing the number, I don't see a variable anywhere.
And the line r = rand_0toN1(6) + 1, what's the + 1 all about? Thanks.
Hai i need help in C++.. this is my code. By using this code I have to alter it and do Evolutionary Text/ Poem.
The poem is :
**“Berburu ke padang datar,
Dapat rusa berbelang kaki,
Berguru kepalang ajar,
Bagai bunga kembang tak jadi.” **
**There are 3 files.. Evo0.cpp(below code), mtrand.h and mtrand.cpp Click Here **
#include <iostream>
#include <ctime>
#include <windows.h>
#include <fstream>
#include "mtrand.h"
using namespace std;
int main () {
const int chromosome_length = 40;
const int pop_size = 20;
int max_generation = 200;
int mutate_position; // pos to mutate
int xover_position; // pos to xover
int rand_val; // to hold random value, i.e. allele
MTRand_int32 mt; // create MTRand object
mt.seed( time(NULL) ); // seed the RNG object
MTRand mtreal; // create MTRand object, real value of [0, 1) interval
mtreal.seed( time(NULL) ); // seed the RNG object
int pop[ pop_size ][ chromosome_length] = {0}; // un-init pop
int mating_pool[ pop_size ][ chromosome_length] = {0}; // un-init pop
int best[ chromosome_length ] = {0}; // un-init pop
int best_fitness = 0; // var to store best[] fitness value
int total_fitness = 0; // var to store total sum of fitness values
double avg_fitness = 0.0; // var to store avg fitness value
int fitness_values[ pop_size ]; // array to store fit value for all ind
ofstream myfile;
myfile.open ("output.txt");
// randomize pop here!----------------------------------------
for ( int i = 0; i < pop_size ; i++ ) {
cout << i << ": ";
for ( int j = 0; j < chromosome_length; j++ ) {
// get random value
//srand ( time(NULL) ); /* initialize random seed */
rand_val = 0; // re-init random value
rand_val = mt() % 2; /* generate random value - 0 or 1 */
pop[ i ][ j ] = rand_val;
//Sleep(1000);
cout << pop[ i ][ j ];
} // end for - inner loop
cout << endl;
} // end for - outer loop
cout << endl;
// randomize pop ENDS!----------------------------------------
int gen_num = 0; // init gen num
while ( gen_num < max_generation ) {
// re-init total & avg fitness values
total_fitness = 0;
avg_fitness = 0.0;
// output best ind here - use (highest) fitness value
int ind_fitness; // declare var for fitness
for ( int i = 0; i < pop_size; i++ ) {
ind_fitness = 0; // re-init fitness value
for ( int j = 0; j < chromosome_length; j++ ) {
ind_fitness = ind_fitness + pop[ i ][ j ];
} // end for - calc fitness value for one ind
fitness_values[ i ] = ind_fitness; // store every ind fitness
//compare current ind with (currently) best ind here
if ( ind_fitness > best_fitness ) {
for ( int k = 0; k < chromosome_length; k++ ) {
best[ k ] = pop[ i ][ k ];
} // end for loop - copy best ind
best_fitness = ind_fitness; // copy the current fitness into best ind
} // replace the best ind with current ind
// output (currently) best ind here - just to have a look!
cout << gen_num << ":" << i << " Current best ind: ";
// loop to print out best chromosome
for ( int m = 0; m < chromosome_length; m++ ) {
cout << best[ m ];
} // end for - print out best chromosome
cout << gen_num << ":" << i << " Current Best Fitness value: " << best_fitness << endl;
// summation of ind fitness values
total_fitness = total_fitness + fitness_values[ i ];
} // end for - calc fitness value for all ind
// avg fitness here!
avg_fitness = total_fitness / pop_size;
// dump data here!
myfile << gen_num << " " << best_fitness;
myfile << " " << avg_fitness << endl;
// parent selection----------------------------------------
int parent1;
int parent2;
int selected;
int z = 0;
int k = 2; // tournament selection parameter
// parent - tournament selection method
for ( int count = 0; count < pop_size; count++ ) {
parent1 = mt() % pop_size; /* generate random value, [0,pop_size) */
parent2 = mt() % pop_size; /* generate random value, [0,pop_size) */
if ( fitness_values[ parent1 ] > fitness_values[ parent2 ] ) {
selected = parent1;
} else {
selected = parent2;
}
for ( int m = 0; m < chromosome_length; m++ ) {
mating_pool[ z ][ m ] = pop[ selected ][ m ];
} // end for - copy winner into parent pool
z = z + 1; // increment parent pool counter
} // end for - loop each two individual
// print out parent pop
// parent selection ENDS----------------------------------
// xover here----------------------------------------
int p1[ chromosome_length ]; // temp parent1
int p2[ chromosome_length ]; // temp parent2
int offspring[ pop_size ][ chromosome_length ]; // offsprings array
int j = 0; // counter for index of 2nd parent
// prob of recombination
double Pc = 0.6; // arbitrary threshold value (higher than Pm)
double prob_recombine; // var to hold the generated prob
for ( int i = 0; i < pop_size; i = i + 2) {
j = i + 1;
for ( int k = 0; k < chromosome_length; k++ ) {
p1[ k ] = mating_pool[ i ][ k ];
p2[ k ] = mating_pool[ j ][ k ]; // p2 gets the next ind
}
//copy the chromosome array, i.e. the ind
for ( int z = 0; z < chromosome_length; z++ ) {
offspring[ i ][ z ] = p1[ z ];
offspring[ j ][ z ] = p2[ z ];
}
// get random position here for xover
// NO NEED to seed RNG object, already hv list of random numbers
//mt.seed( time(NULL) ); // seed the RNG object
xover_position = 0; // re-init pos value
// NEED to CHECK LOWER VALUE: should be
// 0 till (chromosome_length - 1)
xover_position = mt() % chromosome_length; /* generate xover position */
prob_recombine = mtreal();
// do recombination if prob LESS than threshold!
if ( prob_recombine < Pc ) {
for ( int counter = xover_position; counter < chromosome_length - 1; counter++ ) {
offspring[ i ][ counter ] = p2[ counter ];
offspring[ j ][ counter ] = p1[ counter ];
} // end for - loop for xover starting from xover_position
} // else here is just to display, actually no need!
else { // DO NOT do recombination if prob GREATER than threshold!
// maintain offspring i and j values as is!
cout << gen_num << ":" << i << " did not do recombination" << endl;
}
} // end for - loop select 2 parents
// xover ENDS----------------------------------------
// mutate here----------------------------------------
// prob of mutation
double Pm = 0.4; // arbitrary threshold value (lower than Pc)
double prob_mutate; // var to hold the generated prob
// go thru ALL ind
for ( int i = 0; i < pop_size; i++ ) {
// get random position here
// NO NEED to seed RNG object, already hv list of random numbers
//mt.seed( time(NULL) ); // seed the RNG object
mutate_position = 0; // re-init pos value
mutate_position = mt() % chromosome_length; /* generate position */
prob_mutate = mtreal();
// do mutation if prob LESS than threshold!
if ( prob_mutate < Pm ) {
// bit-flip the value at position
if ( offspring[ i ][ mutate_position ] == 0 ) {
offspring[ i ][ mutate_position ] = 1;
} else {
offspring[ i ][ mutate_position ] = 0;
} // end if-else bit-flip
} // else here is just to display, actually no need!
else { // DO NOT do mutation if prob GREATER than threshold!
cout << gen_num << ":" << i << " did not do mutation" << endl;
}
} // end for - mutate all ind
// mutate ENDS----------------------------------------
// survivor select here----------------------------------------
// since offspring is NOT in pop[][],
// so MUST write back into pop[][]
for ( int i = 0; i < pop_size; i++ ) {
for ( int j = 0; j < chromosome_length; j++ ) {
pop[ i ][ j ] = offspring[ i ][ j ];
} // end for - loop each ind
} // end for -loop write offspring into pop
// survivor select ENDS----------------------------------------
gen_num = gen_num + 1; // increment gen num
} // end while loop - GA finish
// output end best ind here
// output (the final) best ind here - just to have a look!
cout << "FINAL best ind: ";
// loop to print out best chromosome
for ( int j = 0; j < chromosome_length; j++ ) {
cout << best[ j ];
} // end for - print out best chromosome
cout << " FINAL Fitness value: " << best_fitness << endl;
myfile.close();
return 0;
} // end main
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
class members
{
private:
int Age;
int Money;
public:
void setAge(int age) {Age=age;}
void setMoney(int money) {Money=money;}
int getAge()const {return Age;}
int getMoney()const {return Money;}
members(int age=0,int money=0): Age(age),Money(money) {}
};
int main()
{
vector<members>v_members;
for(size_t i=0,z=0;i<10;++i,++z)
{
if(z!=5) { v_members.push_back(members(50,70)); }
}
}
I wrote a litte program for a better understanding of a classvector and costructors. It should be ok but there are two questions.
How could one insert new elements in the vector ?
Would it be a good idea to create the vector within the class / the constructor?
If so, how could this be done and how could data then be saved in the main?
What should I be using? Should I be using _T? or L? Or Neither?
I know some functions end with the A for Ansi and some end in W for the Unicode version but I have no clue what I want to use.
if I use _T would I have to change all my strings to wstrings? if I use L would I have to do that too?
if I use _T would I have to change all my MessageBoxes to MBW or MBA or just MB? What about StrLen would I change that too? Also some functions require lengths vs character bytes. Does this affect it?
Ohh and I almost forgot. What is the difference between _Unicode and Unicode :S
I need to modify the following program to store person objects instead of integers. Include a function to input person data from the keyboard in the person class (similar to the readRecord() function). Also add a non class function to display the list contents.
Include a separate search function (search on the name of the person) which returns the position in the list of the item if found
Setup a menu to access the different functions such as:
1 Build a list
2 Search list
3 Add to list
4 Delete from list
5 Display list
This is the code:
#include <iostream>
using namespace std;
// Linked list using structures
struct nodeType {
int info;
nodeType *link;
};
nodeType* buildListForward()
{
nodeType *first,*newNode, *last;
int num;
cout<<"enter numbers";
cin >>num;
first=NULL;
while(num!=-999)
{
newNode = new nodeType; // create new Node
newNode->info =num;
newNode->link = NULL;
if(first==NULL) // special case empty list
{
first = newNode;
last= newNode;
}
else
{
last->link = newNode;
last = newNode;
}
cin>>num;
}
return first;
}
nodeType* buildListBackward()
{
nodeType *first,*newNode;
int num;
cout<<"enter numbers";
cin >>num;
first=NULL;
while(num!=-999)
{
newNode = new nodeType; // creat new node
newNode->info =num;
newNode->link = first;
first = newNode; // keep adding at beginning
cin>>num;
}
return first;
}
nodeType* deleteNode(nodeType *head,int delItem)
{
nodeType *current,*prev;
bool found=false;
current = head;
prev = head;
while(current!=NULL && !found) { // search loop
if(current->info==delItem) found = true;
else {
prev = current;
current = current->link;
}
}
if(found) {
if (current==head) head = current->link;// special case delete head
else
prev->link = current->link;
delete current;
}
return head;
}
nodeType* insert(nodeType *head, int item)
{
nodeType *current,*prev,*newNode;
bool found=false;
newNode = new nodeType;
newNode->info = item;
newNode->link = NULL;
current = head;
prev = head;
while(current!=NULL && current->info<item) { // search loop
prev = current;
current = current->link;
}
if (current==head) { // special case add at head
newNode->link = current;
head = newNode;
}
else {
prev->link = newNode;
newNode->link = current;
}
return head;
}
int main() {
nodeType *head, *current;
system("pause");
return 0;
}
Hi all,
I have a rather basic C/C++ question about the priority of the ++ operator in regard to pointers. Note the following code (joining two strings):
Now the function mystrcat joins lastname to name but I don't understand exactly why. At the end of the 1st while loop (line 3) base should be pointing to the terminal zero (\0) of the base string, right?
Now, the second while loop (line 4) I don't understand. What happens first? The assignment (*base)=(*add) and the increment of pointer positions? Or the other way around? First increment of position, and then assignment. I don't quite understand the prioritizing of actions in the 4th line.
Im making a program in wich I need to monitore (import) a variable (number from an other program window every time the variable changes. There are very much other information in this window but I only want this number that is occuring at a sertain position in the window. How do I do this? with hooks?
Greatful for answeres.
Hello everyone, I want to start learning C++, because that's what we do at school and I really need to know it. But there's a problem, I don't know where to start from, what to do and such. At school I can't understand anything from the teacher, so that won't work. I tried reading some books, but they don't explain very well, or I just simply can't understand.
I come from a poor country, so we use TurboC++ to code at school, it's really dumb, but yeah, can't do anything about it.
At school, we do exercises with numbers and arrays, for example, the program reads numbers until meeting 13, show the even and uneven ones, show the average, show the negative/positive ones. Or the program reads numbers until n, show the sum of the middle numbers, like 12345, show the sum of 3 and 4. Or the minimum and maximum value of something.
Can anyone recommend me what to do to properly learn C++ and do these exercises? I'll have a lot of C++ exams in the future and I wanna do well, also I need this knowledge of C++ for later use.
Thanks for reading, sorry for the spelling mistakes and sorry if it already has been answered or I posted in the wrong place!
Hello, I am trying to create a Login system, so far it writes users correctly however it doesn't seem to be reading it correctly as it always claims the username/password is incorrect even though when I check the file it is.
I'm trying to implement SoRayPickAction that will, when the mouse is clicked, select a particular node so then I can translate, rotate, etc. I have three nodes: desk, lamp, and frame (picture frame). However, I don't think that my code is at all right. I also have various methods such a MouseButtonCallback (which will check if the mouse is clicked and then use a navigator) and MouseMoveCallback (same idea). So here's the code that I have, but do you have any suggestions? Right now, well, it doesn't do anything.
Might you also know of an action in OpenInventor that can "place" a node in the scene, i.e. place the lamp on top of the desk, frame on the wall, etc. Is it with paths? I don't even know what I'm looking for, unfortunately. Thanks so much for your help!!
Hello,
I'm fairly new to programming, and I'm not exactly sure how to do line-rect collision detection. If it helps, I'm using SFML 2. Can someone explain to me how I would go about coding line-rect collision detection?
Thanks in advance.
and my problem is that in the desc field, when I must insert something, it skips over, passing to the type field, not letting me insert anything. I've tried in another project only with the getline(cin, desc, '\n') and it worked, it took all the line, but here it just skips the field. My question is this: why does this thing happens? and did I do something wrong?
10x.
I have run into a bit of a problem with regards to application startup...
I have written a C++ application with QT libraries that uses active QT to communicate with our ERP system in our business, the requirements are that any application we use needs to communicate its variables into this application by means of an argument list that uses unique splitters, and the application then checks the command (seperate argument) and handles the variables and inserts into XML to communicate them to the ERP
my issue is this, with larger argument lists (larger applications and more intricate functionality) the application take much longer to start up, functionality from the very first coding line to the finish is quick, as quick as I can possibly get it... but the startup is way too slow...
Is there anything I can do to speed up the startup? can this be caused by the large arguments? or could it be something else, I thought of dll loading as a possibility though I have tested running the application over a network and on the same machine (because to my knowledge dll loading takes even longer over a network) but I found exactly the same result
I'M working my way through the book "C++ without fear by Brian Overland" and there are two small programs with to totally different types of type casting and the book fails to explain the difference, please help me understand. Thanks. The first one is on a while loop and the second one is on a for loop.
prime1.cpp
using namespace std;
int main()
{
int n; // number to test for prime-ness
int i; // loop counter
int is_prime; // boolean flag
// assume that a number is prime untio proven otherwise
is_prime = true;
// get a number from the keyboard
cout<< "Enter a number and press ENTER: ";
cin>> n;
// test for primeness by checking for divisiblity by all whole numbers from 2 to sqrt(n)
i = 2;
while(i <= sqrt(static_cast<double>(n)))
{
if(n % i == 0)
is_prime = false;
i++;
}
// print results
if(is_prime)
cout<< "Number is prime.";
else
cout<< "Number is not prime.";
system("pause");
return 0;
}
prime2.cpp
#include <Stdafx.h>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n;
int i;
int is_prime;
// assume that a number is prime until proven otherwise
is_prime = true;
// get a number from the keyboard
cout<< "Enter a number and press ENTER: ";
cin>> n;
// test for prime-ness
for(i = 2; i <= sqrt((double) n); i++)
{
if(n % i == 0)
is_prime = false;
}
// print results
if(is_prime)
cout<< "Number is prime.";
else
cout<< "Number is not prime.";
system("pause");
return 0;
}
I have been researching ways to make a DOS window disappear when starting a program. I have solved this, by using getconsolewindow() and setwindow(). The thing is, I still get a blip where the DOS appears for a couple miliseconds. Is there a way to fix that?
Need a little help please:
i have been trying to complete this for a couple days but i get more and more confused everytime i try.
When an object is falling because of gravity, the following formula can be used to determine the distance the object falls in a specific time period.
D = ½ gt^2
The variables in the formula are as follows: d is the distance in meters, g is 9.8, and t is the amount of time in second that the object has been falling.
Write a function named fallingDistance that accepts an object’s falling time (in seconds) as an argument. The function should return the distance, in meters, that the object has fallen during that time interval. Write a program that demonstrates the function by calling it in a loop that passes the values 1 though 10 as arguments, and displays the return value.
*Additional to this problem my prof wants two functions that calculate the falling distance.
function 1 passes arguments by value
function 2 passes argument by reference
outputs should be in form of a table
whats confusing is the prof established that in the main it should resemeble like this:
for(--------------)
call (by value)
output
call by ref works fine but call by value only works when i put double d as global but then it only comes back as 0's in the output. its not reading the equation
my code so far:
Inline Code Example Here
# include <iostream>
# include <cmath>
# include <string>
using namespace std;
void fallingDistance2(double &);
double fallingDistance1(double);
const double g = 9.8;
int t;
double d;
int main()
{
cout<<"calculated by passby values.\n";
cout<<"Time \t\t Distance\n";
cout<<"-------------------\n";
for (t=1;t<=10;t++)
{
fallingDistance1(d);
cout<<t<<"\t\t"<<d<<endl;
}
cout<<"calculated by reference values.\n";
cout<<"Time \t\t Distance\n";
cout<<"-------------------\n";
for (t=1;t<=10;t++)
{
fallingDistance2(d);
cout<<t<<"\t\t"<<d<<endl;
}
return 0;
}
double fallingDistance1(double d)
{
d=0.5*9.8*t*t;
return d;
}
void fallingDistance2(double &refd)
{
refd=0.5*9.8*t*t;
}
i have read a txt file into queue just like below example which is i can do it.. the problem is i how to read Tab Delimited Files which i want file size to multiple by 0.6... because i want to create handle a printer simulation using queue...sorry for my english
Name of File Time accepted File size (KB)
Exercise.cpp 8.00 am 1.2
Report.doc 8.00 am 3.4
Test.doc 8.10 am 5.0
Hello I am looking to read a file into a 2d array to show which spaces have been taken/ haven't taken whiey will show a # if not taken and a T if taken, so far I just have a text file I created which shows like this:
T # # T
T T T #
All I am trying to do at the moment is to read this into a 2d array and display it as above, later on I will allow users to choose a position and take a space of the layout (changing a T to a #) and then I will want to save it to the file to make the changes.
But at the moment all I want to do is show it, this is what I have so far, I appologize if it's messy, I have made so many changes now to try and get it to work.
I hope someone can offer som guideance.
void Layout::layoutset(void)
{
ifstream myFile ("layout.txt", ios::in);
myFile.precision(2);
myFile.setf(ios::fixed, ios::showpoint);
myFile >> spaceLayout[2][5];
while (!myFile.eof())
myFile >> //Don't know what to put here
while (!myFile.eof())
{
for (int r = 0; r<2; r++)
{
for (int c = 0; c < 5; c++)
{
spaceLayout[r][c] = //?Don't know what to put here
}
}
}
myFile.close();
}
Hi!
In my program MFC Doc/view one view constantly displaying what the camera is "seeing". After some event I want to show in the other window - dialog the image that has been in the view in the moment of event.
I have code in Dialog window that succesfully draws pictures from disk. However it starts it's work with Handle and "LoadImage". When I try to pass a HANDLE from view no errors occure but no picture displays. The same situation when I pass CBitmap * with some modification of code.
Exploring structures I found that every bit of data like "Height", "Width" goes fine. But it seemed to me that there are some problems with pointer to picture data. Si I decided to copy data from pointer in view to pointer of picture data in dialog manualy with memcpy()
And when I get "Access violation writing location 0x000000a4". 0x000000a4 - is the start address of tBm.bmBits by the way.
So questions)
What can be a good conception of realising my idea, generally? Did I choose right strategy or i should solve this problems in some other way? Just In common words, can someone show me the goodstyle direction or so?
And just practice question about this violation in memcpy. Howto copy this bits correctly in physically another memory in ohter structure?
int main(){
/** Declare classes **/
for(long int i = 0 ; i < 50000 ; i++){
class Rahim *rahim = new Rahim( (unsigned)(i));
class Bahram *bahram = new Bahram;
class Asgar *asgar = new Asgar;
/*****Body of the code******/
throw( asgar, bahram , Rahim );
delete (bahram);
delete (Rahim);
delete (asgar);
}//end for
return 0;
}
void throw(class Asgar *asgar, class Bbahram *bahram ,class Rahim *Raahim ){
/** Declare variables **/
long int time;
long int step = 1999;
/** Time Loop **/
for( time = 0 ;time < GT ;time++ ){
get_bahram( bahram, Rahim );
asgar -> get_coordinates ( bahram , time );
if(step == time){
long int time_Rg = (step + 1);
asgar -> calculate_r ( time_Rg );
step += 2000;
}//end if
} //end for
} //end function
.
Hello all. I have come to the conclusion that when i try to use images for backgrounds in my windows forms, these images have to be exactly the same size as the form or else when i move the form it will cause the form to shake. The problem with doing this is when i maximize the form the texture image i used as a background then will tile and repeat over and over to match the size of the form. What i want to do , is to use a very large and complete texture or image for background, but only load in part of it and that part it the forms width and height. Then when i resize the form to be larger, i can once again draw the image, but an increased ammount of the image from file . So ill only draw part of the image, and thats the part i need and nothing more. I have struggled for days on how this would work. please help thanks for any tips.
I have read a file with around 120k words so i try to do it fast. have seen the:
int x = setvbuf(fp, (char *)NULL, _IOFBF, BSZ);
assert( x == 0 && fp != NULL );
option but it takes more than a second ( 1 mb file) so now i tried this method :
f
open_s (&pFile,DICT,"rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
how do i continue from here? buffer holds a list of words and i want to get them one by one as fast as possible because im building a multimap with those words.
I am using visual studio 2010. I wanted to compile my cpp from cmd. I can compile it using "cl file.cpp" comand in visual studio developer command line tool.
But I wanted to compile it from the built in cmd of windows. When I try to use the command "cl file.cpp" it does not recognize the command. I even tried to cd to cl.exe path and run from there but then it gives a mspdb110.dll is missing error.
I herd that we need to put environment variables but I am not able to find anywhere which variables to set.
Can you tell me how can I make my application recognizes when the user presses a button on keyboard? For example: presses 'S', application prints "Hello.".
I need this information for BorlandC++, but it would be useful even though you provide the same for VC++ :) (I am not talking about console applications, I need these tips for GUI apps )
I'M trying to compile a very small cout<< console application in MSC C++ but the program flashes up and goes away so quick that I can't see anything that's going on. Below are my headings, what's missing? Thanks.
#include <Stdafx.h>
#include <iostream>
using namespace std;
Please write a program that will asks to give an integer number K that will be higher than 20.
If the number is not higher than 20 then make the program to show a relevant message and then ask to insert again the number K.
After that, depending on the users choice:
If he/she presses 1, it will be shown the sum of numbers from 1 to K.
If the number is 2, it will be shown the odd numbers from 1 to K.
If the number is 3, the program will end.
If any other numbers are inserted then make your code to show a warning message (that the user must insert numbers from 1 to 3) and then the program must do again the process of inserting the number 1-3.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int k;
cout<<"\n Insert a number greater than 20. ";
cin>>k;
cout<<"\n The number is "<<k<<" ."<<endl<<endl;
while ( k<=20 ) {
cout<<"It must be greater than 20. Give again the number. ";
cin>>k;
}
int num, sum, odd;
cout<<"\n Now,give a number from 1 to 3. ";
cin>>num;
cout<<endl;
switch (num)
{ case 1: {sum = 0;
for ( int i=num ; i<=k ; i++)
sum+=i;
cout<<"The sum from "<<num<<" to "<<k<<" is: "<<sum<<endl;
}
break;
case 2: { int i = 1;
cout<<"\n The odd numbers from 1 to "<<k<<" are:\n";
for ( int i=1 ; i<=k ; i=i+2 )
cout<<i<<" ";
cout<<"\n";
odd=i++;
}
break;
case 3:
break;
default: {cout<<"The number must be 1, 2 or 3.\n";
cout<<"\n Give again the number ";
cin>>num; cout<<"\n";
}
break;
}
cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
I am 100 % sure it has to do with my value being a string but I haven't found anything helpful elsewhere, even though I've searched hard (in my opinion). So please, can anyone help me? I'm still a beginner in programming but a superficial explanation will do :)
Write a program for an application that does not tolerate erroneous input data. Therefore, the data values are prepared by entering them twice by the user. Two lists are made by getting positive integers from the user, separated by a negative number. These two lists of numbers should be identical; if they are not, then a data entry error has occurred.
• Example:
User enters list
17
14
8
-5
17
14
8
The lists are identical. However see the following input
User enters list
17
14
8
-5
17
12
8
Program should show data entry error.
Write a program that asks the user for a word, and then prompts a user for a letter. Your program should count the number of times the letters entered appear in the word, and then continue prompting for new letters. The program should list the letters found and number of times they appear in the word.
Sample Run:
Enter a word: hello
Enter the letter (enter zero to quit): a
There are 0 a’s
Enter the letter (enter zero to quit): h
There are 1 h’s
Enter the letter (enter zero to quit): 0
I cant display this output..how i can i declare the gender n relate it with my price..i stuck here..oop c++
i have 2 coding for this..which 1 is better..im new in this progrmmer..
void eSalon::priceCurling()
{
cout<<"\nYour Gender is: "<<gender;
if (gender=female)
{
cout<<"Long Hair Rm30-RM49"<<endl;
cout<<"Short Hair RM50-RM100"<<endl;
}
else if (gender=male)
{
cout<<"Long Hair RM46-RM70"<<endl;
cout<<"Short Hair RM20-RM45"<<endl;
}
or this 1,,
void eSalon::pricePerm()
{
cout<<"\nYour Gender is: "<<gender;
if (gender=female)
{
longHair=50-100;
shortHair=30-49;
}
else if(gender=male)
{
longHair=46-70;
shortHair=20-45;
}
Hi,
I have a matrix of size of n x m, how can the file be read without any given size, thus making it possible to be read with any given size matrix?. Here is the scenario, I have a matrix of size 3 x 2 then someone wants to use use my program and he has a file with say matrix of size of 8 x 10...the program should handle any matrix size.
The second example which Hate to do seems like so much more work. Not only that but I'd have to constantly switch back and forth between headers and sources to see whats declared where or what contains what. But now I'm looking up all my habbits to see if they cause performance degradation and I've read the first one does whereas the second doesn't :S
I'm also reading that if i put my definitions inside the class, it's automatically inlined and that if I put the inline keyword in there then it's even worse :S Should I just leave them in there as inline and if not then why? Is there a way to define them inside the class and NOT be inlined?
Is this true? Am I actually doing something bad? I'm being told to never put the definitions in a header.. Only declarations.. Apparently it slows down compile time and slows down my program which is what I read at stack overflow from someone asking a similar question. I use header guards by the way.
I just really don't like having that many unneccesary files when I can just include my header with everything in there already..
So is it bad? Also why should a coder use the scope operator like that instead of putting it all inside the class? Is there an advantage such as performance/compile time or is it just style? C# doesn't seem to care whether or not everything is in one file..
I used to use a tutorial for windows console API, but the website was taken down :(. So now I need to ask how to do these things (which ALL were included on the website) in the console with windows API:
I am a brand new programmer, just learning from the web, i wrote this function as part of an accounting program to write stored values to an output file, the program compiles, and runs without any problems, but when i activate this function from within the program nothing happens, when i retrieve the values from the file, they are exactly the same as the last time i drew from the file. HELP!
I want to start developing an IDE or at least a Syntax highlighter into my program. Atm it's a simple text editor with basic copy paste functions.
How does Notepad++ do it? Is there a way I can integrate that into my own program? If not then I'll write it on my own. Also how does codeblocks compile our programs. I read that VC++ took 17 years to be created so how come codeblocks is so new and yet it compiles sourcecode :S
Also if codeblocks is using a backend compiler can I use that same thing in my program or is it going to take me years too?
My understanding of getopt is very limited.
I do however realise that argv[0] is the exe file, argv[1] is the option, argv[2] is the word to compare and argv[3] is the dictionary or document I want to search(file .txt).
I'm trying to set a pointer to the dictionary and then iterate through it to see if there is a match with the argv[2] (input word) to the text file, and if there is a match out put the argv[2] word.
Below is my current code that has errors
main.cpp:61: error: no match for 'operator==' in 'list == (argv + 12u)'
main.cpp:64: error: no match for 'operator' in '*list'
Any help would be greatly appreciated.
#include <cstdlib>
#include <unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main(int argc, char** argv) {
enum {
WHOLE, PREFIX, SUFFIX, ANYWHERE, EMBEDDED
} mode = WHOLE;
bool jumble = false;
bool ignore_case = false;
bool invert = false;
string length = "0,0";
int c;
string input;
vector <string> list;
vector <string>::iterator i;
while ((c = getopt(argc, argv, ":wpsaejivn:")) != -1) {
switch (c) {
case 'w': mode = WHOLE;
break;
case 'p': mode = PREFIX;
break;
case 's': mode = SUFFIX;
break;
case 'a': mode = ANYWHERE;
break;
case 'e': mode = EMBEDDED;
break;
case 'j': jumble = true;
break;
case 'i': ignore_case = true;
break;
case 'v': invert = true;
break;
case 'n': length = optarg;
break;
default: WHOLE;
break;
}
}
argc -= optind;
argv += optind;
switch (mode) {
case WHOLE:
while(argc != -1){
list == argv[3];
for(i == list.begin(); i != list.end(); i++)
if(argv[1] == argv[3]){
cout << *list << endl;
}else cout << "Did not work again" << endl;
}
}
return 0;
}
I just downloaded netbeans and when I went to start a C++ project I was told that Netbeans couldn't find a C++ compiler. When I use to play around witt MS Visual C++ I never ran into a problem like this, Can anyone tell me what's up and what I can do about it? Also, though I want to learn to program I might as well learn a language that can get me a job. What is the beast language out there to get you hired? Thanks again.
I'm trying to write a function that enlarges a dynamically allocated array, but I am having some trouble doing so. Here's my code:
void enlargeArray(int *oldArr, int arraySize)
{
//oldArr is a dynamically allocated array
int *newArr = new int[arraySize*2];
//copy the elements from oldArr into newArr
delete oldArr[];
oldArr = newArr;
}
However, although newArr gets created correctly, when I examine the contents of oldArr in my main function (where I call enlargeArray from), oldArr is unchanged. Does anyone have any tips for how to modify oldArr itself? Thank you.
please help me coding this in c++:
- Inverse matrices.
- Calculate matrix determinant.
- Set a row or a column of the matrix to a certain value.
- Calculate performance (time and memory taken by each algorithm).
i left out del for delete. the user should also be able to delete an item they previously added so it wont be displayed at the end. i am confused on how i would go about this etc. everything else works.
any help is much appreciated.
I am familiar with loops, functions, recursions, (though I have praticed some questions, it is troubling to get the hang of it completely), passing by value, reference and ofcourse pointers. I can work with arrays and 2d arrays.
This is my second project. My first project was hangman. My sir wasn't impressed if he did approve of what I made. This time, I wish to do better. I am willing to work harder but this project marks means alot. I want to ask you, is blackjack a better option to make my c++ project or checkers? I prefer checkers but I don't want to make the wrong descicion and get stuck because this time the deadline is quite near.
ComplexAttrib is a custom data type. It has operator overloading functions such as add, multiply etc.
n1.Set(f1)
n2.Set(f2)
Here we are setting FloatAttribute instances in our general purpose attribute.
out = n1 + n2
This should call add operator function defined in FloatAttribute class & out should become FloatAttribute
n1.Set(c1)
n2.Set(c2)
Here we are setting ComplexAttribute instances in our general purpose attribute.
out = n1 + n2
This should call add operator function defined in ComplexAttribute class & out should become ComplexAttribute
I am reading couple of books and also googling but still I am not sure how do I implement.
How to create NAttrib, FloatAttribute and ComplexAttribute class?
I am not sure but Template Class could be a solution?
please help me coding this in c++:
Inverse matrices.
Calculate matrix determinant.
Set a row or a column of the matrix to a certain value.
Calculate performance (time and memory taken by each algorithm).
hi im currently learning about linked list. Ive created a code which is supposed to let you type some numbers, then display them. i did this mostly by using information on the internet(code examples) and such. Hence there are obvious mistakes a bits i do not understand. Here is my code:
#include <string>
#include <cstdlib>
typedef enum {Dominion, Sobeys, Shoppers, Walmart} Store;
using namespace std;
class Item
{
private:
// name of the item (non-empty string)
string name;
// number of dollars in price of item
int dollars;
// number of cents in price of item
int cents;
// store where item is sold
Store whereToBuy;
// number of items to buy
int numToBuy;
public:
// Default constructor for Item class. Should set all fields to 0.
Item();
// Constructor for Item class
Item(string name, int dollars, int cents, Store whereToBuy, int numtoBuy);
// Returns the name of the item
string getName();
// Returns the cost of the item in dollars
// Postcondition: dollars' >= 0
// cents' >= 0
// (dollars' > 0) or (cents' > 0)
void getCost(int* dollars, int* cents);
// Returns the store where the item is sold
Store getStore();
// Returns the quantity of the item to buyd
int getNumToBuy();
// Sets the name of the item
// Precondition: name should be a non-empty string
void setName(string name);
// Sets the cost of the item in dollars
// Precondition: (dollars >= 0)
// (cents >= 0)
// (dollars > 0) or (cents > 0)
void setCost(int dollars, int cents);
// Sets the store where the item is sold
void setStore(Store store);
// Sets the quantity of the item we want to buy
// Precondition: numToBuy > 0
void setNumToBuy(int numToBuy);
};
class ShoppingListNode
{
private:
Item thisItem;
ShoppingListNode* next;
public:
ShoppingListNode(Item item)
{
thisItem = item;
next = NULL;
}
ShoppingListNode(Item item, ShoppingListNode* nextNode)
{
thisItem = item;
next = nextNode;
}
};
class ShoppingList
{
private:
ShoppingListNode* headNode;
public:
// Creates an empty shopping list
ShoppingList();
// Constructor for a shopping list.
// Precondition: items should point to an array of length numItems
// Postcondition: After constructor is run, it should consist of numItem nodes with the items in the list the same as those in
// the input array items and in that order.
ShoppingList(Item* items, int numItems);
// Constructor for a shopping list
// Postcondition: (headNode->thisItem)' = item
// (headNode->next)' = restOfList
ShoppingList(Item item, ShoppingListNode* restOfList);
// Prints the names and prices of the items on the shopping list in
// non-decreasing order of price per unit
// Items should be printed out one per line - name first followed by a tab and then the price in the format $x.yz,
// where x is the price in dollars, and yz is the price in cents (y and z are two decimal digits, and either or both may be 0).
void printInOrder();
// Returns the total cost of all items in the shopping list. Make sure that the individual price of each item in the list is multiplied by the
// quantity of the item being purchased as given in the numToBuy field.
// Postcondition: *dollars' >= 0
// *cents' >= 0
// *cents' < 100
// *dollars' = thisItem.dollars
// *cents' = thisItem.cents
void getTotalCost(int* dollars, int* cents);
// Adds item to the shopping list
// Postcondition: If an item with the same name, location and price is already present in the list,
// then the numToBuy field of the item in the list is incremented appropriately
// Otherwise item is added as a fresh node to the list.
bool addItem(Item item);
// Removes item from the shopping list
// Postcondition: item is not present in the list after function execution
// result is true if item was successfully removed
// result is false if it wasn't in the list to begin with.
bool removeItem(Item item);
// Postcondition: result is true if the shopping list is empty and false otherwise.
bool isEmpty();
// Returns the number of stores where items have to be purchased from.
// Postcondition: result >= 0
int numStores();
};
This is .h file.
And following this is my cpp file . Please help me to resolve the printInOrder function, I have problems for reading the contents of everyNode, because the headNode->thisItem is not work, because the thisItem is in private.
Thank you
#include "ShoppingList.h"
#include <cassert>
#include <iostream>
Item::Item() {
dollars = 0;
cents = 0;
numToBuy = 0;
}
Item::Item(string name, int dollars, int cents, Store whereToBuy, int numtoBuy) {
name = name;
dollars = dollars;
cents = cents;
whereToBuy = whereToBuy;
numtoBuy = numToBuy;
}
string Item::getName() {
return name;
}
void Item::getCost(int* dollars, int* cents) {
if(*dollars == 0 && *cents == 0)
cout << "error";
cout << "$" + *dollars + '.' + *cents;
}
Store Item::getStore() {
return whereToBuy;
}
int Item::getNumToBuy() {
return numToBuy;
}
void Item::setName(string name) {
assert(name!="");
name = name;
}
void Item::setCost(int dollars, int cents) {
double cost = 0.0;
assert(dollars>=0 && cents>=0 && ((dollars > 0 && cents == 0) || (cents > 0 && dollars ==0)));
cost = dollars + cents % 100;
}
void Item::setStore(Store store) {
store = whereToBuy;
}
void Item::setNumToBuy(int numToBuy) {
assert(numToBuy > 0);
numToBuy = numToBuy;
}
ShoppingList::ShoppingList() {
headNode = NULL;
}
//Constructor for a shopping list.
// Precondition: items should point to an array of length numItems
// Postcondition: After constructor is run, it should consist of numItem nodes with the items in the list the same as those in
// the input array items and in that order. //
ShoppingList::ShoppingList(Item* items, int numItems) {
ShoppingListNode* nextNode;
headNode = new ShoppingListNode (*(items));
for(int i = 0;i<numItems;i++){
nextNode = new ShoppingListNode(*(items + i+1));
nextNode = new ShoppingListNode (*(items+i),nextNode);
}
}
// Constructor for a shopping list
// Postcondition: (headNode->thisItem)' = item
// (headNode->next)' = restOfList
ShoppingList::ShoppingList(Item item, ShoppingListNode* restOfList) {
headNode = new ShoppingListNode(item, restOfList);
}
// Prints the names and prices of the items on the shopping list in
// non-decreasing order of price per unit
// Items should be printed out one per line - name first followed by a tab and then the price in the format $x.yz,
// where x is the price in dollars, and yz is the price in cents (y and z are two decimal digits, and either or both may be 0).
void ShoppingList::printInOrder(){
Item* item;
ShoppingListNode* thisNode = headNode;
ShoppingListNode* nextNode;
int i = 0;
//while(thisNode!= NULL){
thisNode = new ShoppingListNode(*(item+i),nextNode);
cout << (*(item+i)).getName();
thisNode = nextNode;
//}
}
bool ShoppingList::isEmpty() {
if (headNode == NULL)
return true;
return false;
}
int ShoppingList::numStores(){
Item tempI;
Store tempS;
int result1 = 0;
int result2 = 0;
int result3 = 0;
int result4 = 0;
ShoppingListNode* nextN = NULL;
while(headNode != NULL){
headNode = new ShoppingListNode(tempI,nextN);
headNode = nextN;
tempS = tempI.getStore();
if(tempS == Dominion)
result1 = 1;
if(tempS == Sobeys)
result2 = 1;
if(tempS == Shoppers)
result3 = 1;
if(tempS == Walmart)
result4 = 1;
}
return result1 + result2 + result3 + result4;
}
/************************Testing Main Function**************************/
int main() {
int numItems;
ShoppingList A;
cout << "How many items do you want to buy? " << endl;
cin >> numItems;
Item* items;
for(int i = 0;i<numItems;i++){
*(items + i) = Item("Ada",1,2,Walmart,1);
A(items,numItems);
}
A.printInOrder();
return 0;
}
I need to create a program that uses a structure that alocates memory with the new operator. The information must be saved in a file, then displayed. The problem I have is that the program saves only the first character of the words I enter. Could someone please help me make it work.
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <new>
using namespace std;
FILE *f;
struct dog {
char name;
char family;
int age;
}list1, list2;
int i,n,optie;
//File Dog
int file_dog()
{
dog* plist;
cout << " Point the number of dogs you want to enter\n" << endl;
cin >> n;
plist = new (nothrow) dog[n];
f=fopen("Dog.txt","w");
if (plist == 0)
cout << "Error: memory could not be allocated";
else
{
for(i=0;i<n;i++)
{
cout << " Enter the name of the dog - " << endl;
cin >> list1.name;
fflush(stdin);
cout << " Enter the family of the dog - " << endl;
cin >> list1.family;
fflush(stdin);
cout << " Enter the age - " << endl;
cin >> list1.age;
fwrite(&list1,sizeof(list1),1,f);
cout << endl;
}
cout << endl;
fclose(f);
delete []plist;
}
return 0;
}
int display_the_file_dog()
{
if((f=fopen("Dog.txt","r")) == NULL )
{
cout << "Error" << endl;
exit(1);
}
cout << " Date despre ciini" << endl;
cout << " ===================================" << endl;
cout << " | Nr | Name | Family | Age | " << endl;
cout << " ===================================" << endl;
i=1;
fread(&list2,sizeof(list2),1,f);
while(!feof(f))
{
cout << " " << i++ << " " << list2.name << " " << list2.family << " " << list2.age << endl;
fread(&list2,sizeof(list2),1,f);
cout << " -----------------------------------" << endl;
}
cout << endl;
fclose(f);
return 0;
}
int main()
{
system("color 0");
system("color f0");
while (1)
{
cout << " -------------- M E N I U -------------" << endl;
cout << " ----------- Choose an option ---------" << endl;
cout << endl;
cout << " | [1] - Create the file Dog |" << endl;
cout << " | [2] - Display the file Dog |" << endl;
cout << " | [3] - Exit the program |" << endl;
cout << " | ---------------------------------- |" << endl;
cin >> optie; fflush(stdin);
switch (optie)
{
case 1: file_dog(); break;
case 2: display_the_file_dog(); break;
case 3: exit(1);
default: printf("Choose the right option\n"); break;
}
}
return 0;
}
I'm working on an assignment that requires me to do the following:
"A file contains 6 numbers per line and contains several records. Another file contains 3 numbers per line and several records. Write a program to input each of the numbers, find the highest number, the lowest number, their total and average. Output the numbers, the highest, lowest, total and average to another file."
Output.txt needs to look like this for each numbers per line:
1 2 3 4 5 6
Min: 1
Max: 6
Total: 21
Avg: 3
The problem I'm having with my code is instructing the computer to read the numbers per line, find the desired math results, output it the aforementioned format, and then repeat the algorithm in the next set of numbers. This is my code so far:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main ()
{
//Declaring variables
ifstream inFile;
ofstream outFile;
int NumPerLine, num, count=0;
int sum=0, min=0, max=0, Total=0, Avg=0;
int row=0, col=0, x, y;
//Opening files
inFile.open("input1.txt");
outFile.open("output.txt");
//************************
//Code data manipulation
//************************
cout << "Processing data."
<< endl;
//Read/Write Integer
inFile >> NumPerLine;
outFile << NumPerLine
<< endl;
//While loop reads data
while (!inFile.eof())
{
inFile >> num;
outFile << num << "\t";
sum = sum + num;
count++;
}//Needs to be solved: how do I run math processes(max,min,avg,total)w/ numbers
//at end of line and THEN continue reading and repeating math processes for next line of numbers?
/*Math processes
//Determining Average
Avg = sum / count;
//Determining Sum
sum = num + sum;
//Determining Max
if(x>y)
max=x;
else
max=y;
//Determining Min
if(x<y)
min=x;
else
min=y;*/
//************************
//End of code data manip
//************************
//Close files
inFile.close();
outFile.close();
return 0;
I have been messing around with making a windows application in Dev-C++ I wanted to make it in a single source file, rather than a project to see if it worked. It did, other than the fact that I got the windows app, AND a DOS prompt behind it. Is there anyway to remove the DOS prompt? I will include the code, so that you can see what I mean.
#include <windows.h>
/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
/* Make the class name into a global variable */
char szClassName[ ] = "WindowsApp";
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
HWND hwnd; /* This is the handle for our window */
MSG messages; /* Here messages to the application are saved */
WNDCLASSEX wincl; /* Data structure for the windowclass */
/* The Window structure */
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */
wincl.style = CS_DBLCLKS; /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);
/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL; /* No menu */
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
/* Use Windows's default color as the background of the window */
wincl.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
return 0;
/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
szClassName, /* Classname */
"Windows App", /* Title Text */
WS_SYSMENU, /* default window */
CW_USEDEFAULT, /* Windows decides the position */
CW_USEDEFAULT, /* where the window ends up on the screen */
544, /* The programs width */
375, /* and height in pixels */
HWND_DESKTOP, /* The window is a child-window to desktop */
NULL, /* No menu */
hThisInstance, /* Program Instance handler */
NULL /* No Window Creation data */
);
/* Make the window visible on the screen */
ShowWindow (hwnd, nFunsterStil);
/* Run the message loop. It will run until GetMessage() returns 0 */
while (GetMessage (&messages, NULL, 0, 0))
{
/* Translate virtual-key messages into character messages */
TranslateMessage(&messages);
/* Send message to WindowProcedure */
DispatchMessage(&messages);
}
/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}
#define ID_BTN 1
#define ID_TEXTBOX 2
static HWND hwndTextbox;
/* This function is called by the Windows function DispatchMessage() */
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) /* handle the messages */
{
case WM_CREATE:
{
hwndTextbox = CreateWindow(TEXT("EDIT"), TEXT("Type Here"),
WS_VISIBLE|WS_CHILD|WS_BORDER|ES_AUTOHSCROLL,
10,10,200,20,
hwnd, (HMENU) ID_TEXTBOX, NULL, NULL);
CreateWindow(TEXT("button"), TEXT("Click Me"),
WS_VISIBLE|WS_CHILD,
10,40,80,20,
hwnd, (HMENU) ID_BTN, NULL, NULL);
break;
}
case WM_COMMAND:
{
//action for button
if (LOWORD(wParam) == ID_BTN)
{
//create variables
int length = GetWindowTextLength(hwndTextbox) + 1;
static char title[500] = "";
GetWindowText(hwndTextbox,title,length);
//MessageBox(hwnd, title, "Debug Box", MB_OK);
// Creates a window displaying the text typed in the box.
SetWindowText(hwnd, title);
}
break;
}
case WM_DESTROY:
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
i make a program with Dev-C++ ..... let say my program is already running now .... if i try to open it ... it show me a MessageBox or an output to tell me i can't run it when is already running
and all other combinations open the file but truncate it.
is this standard behaviour? the reason i ask this is that i find it very wierd that the following combination truncates the file
ios_base::ate | ios_base::out
if this is standard behaviour, then there seems to be no way to use ate with out. i.e create an output stream which doesnt truncate without using app.
please confirm this. and suggest a workaround(if possible for the above problem).
Whenever I create some small tool in c++ dll for use with another language, a new user always has to download
the microsoft redistributable package and install it.
Is there anyway to add the resources needed from the redist, to my dll?
How even do you know what resources it needs to function?
I'm trying to upgrade my class library to my current mathematical skill set and am having trouble with multi-term polynomials, especially those I where I don't know how many terms the user will be putting in. I know that the formula for the first derivative of a polynomial is ax^n = n * ax^n-1; and the second derivative is the derivative of the first derivative. So for example:
Find the derivative of 4x^2:
4x^2 = 2 * 4x^2 - 1 = 8x^2-1 = 8x
Find the second derivative of 4x^3:
4x^3 = 3 * 4x^3-1 = 12x^3-1 = 12x^2
12x^2 = 2 * 12x^2-1 = 24x^2-1 = 24x
Right now I just have an algorithm for the first derivative of a single term polynomial:
// Pesudocode (C++ Syntax):
int Base = 0;
int Exponent = 0;
string Variable = "";
cout << "Please input a polynomial to the first degree in the form (4 y 9): ";
cin >> Base >> Variable >> Exponent;
Base = Exponent * Base;
Exponent = Exponent > 1 ? Exponent - 1 : 0;
Variable = Exponent == 1 ? Variable : Variable + "^";
Variable = Exponent == 0 ? "" : Variable;
string exString = (Exponent == 1 || Exponent == 0) ? "" : (const char*)Exponent;
cout << "The first derivative of the polynomial you submited is: " << Base << Variable << exString << "\n";
Chose to not work on the second derivatives until I figure out the whole parameter problem. I'm sure I have to use arrays or lists to accomplish this, but I'm not sure how the algorithm would work for a polynomial with 3 or more terms:
3x^2 + 13x + 4
Also the derivative of a constant (basically any number without a variable and exponent of 2 or higher) is equal to 0 for those who don't know and the derivative of infinity is undefined.
I continue to use the same C++ libraries for COTS software that we use in my company. Their help files aren't great and when I send queries directly to the company it can be weeks or possibly months before I get a response. This, I think, is a simple problem that I'm hoping anyone who is handy at c++ (ie not me) can have a stab at answering.
I want to get a list of files in a directory that have the file extension 'ext'. I'm pretty sure that I want to use their library function dir_list() with a filter that only include files that have if the last 4 characters as ".ext". However, from their comments, I can't work out how to define this filter function or use it in dir_list(). Can anyone give me some hints, please? Yes, I can work around this, but it would be nice to use what is in the toolbox.
// Function to act as a filter to a directory list.
// This function must return True if a member of the list
// has past the criterion, and False if a member is to
// be excluded from the list due to failure to pass the
// filter criteria.
typedef bool (*filter_func)(const char[], const char[]);
void dir_list(
StringList &file_list, // List of files (returned)
const char dir[], // Directory to scan
filter_func filter = NULL // Filter function
);
The code is really long so I don't want to post all of it, but I'm posting the part I'm having an issue with. This is part of a fraction class I'm writing. Most of it is working but for there is something wrong with the istream because when I enter a fraction it just says d=0.
This is my input overload:
istream& operator>>(istream& in, fraction& x)
{
int a;
int b;
char c;
in >> a >> c >> b;
fraction z=(a/b);
x=z;
return in;
}
This is the part in main:
fraction d;
cout << "Enter a fraction: ";
cin >> d;
cout << "d=" << d << endl;
So; I have to determine if there is a) 3 of a kind b)4 of a kind c)straight.
I have put the 7 cards into a 1 dimensional array and sorted them but I also need a case for not being more than 4 cards. I don't need to include suits.
Here is what I have done:
include<iostream>
using namespace std;
include<cmath>
include<ctime>
include<cstdlib>
include<iomanip>
int main()
{
const int size=7;
int cards[size]={};
const int b=13;
int tem[b]={0};
int a; int p;
srand(time(0));
for(int i=0; i<10; i++)
{ for (int s=0; s<size; s++)
{ cards[s]=1+rand()%13; }
int i = 0, temp;
while( i < size ){
if ( i == 0 || cards[i - 1] <= cards[i] )
i++;
else{
temp =cards[i];
cards[i] = cards[i - 1];
cards[--i] = temp;}}
for (p=0; p<b; p++)
{tem[p-1]++;
if(tem[p]==3)
for (int m=0; m<size; m++)
cout<<setw(4)<<cards[p]; cout<<"Three of a kind. ";
cout<<endl;} }
system("pause");
return 0;
}
it does not work though
4 of a kind is about the same as 3 of a kind
no idea for the straight
So let me start by saying that I am a complete beginner when coding in C++ windows/forms program. I was able to get my SQL database connection up with my program. I've ran some simple tests and it looks like my program is able to do simple queries such as inserting values into a table and such. My real hope, now, is for me to have my program take what's in one of my textboxes (username textbox for this example) and put it into my SQL database (Polynomigra), table (logins), field (username). I have not a clue how the syntax goes for this query. I also have no idea why the data type "string" is not existent in C++ windows forms applications. Can someone help me out? And again, I mention to you all that I am a complete beginner at this--I'm teaching myself how to do this.
I'm writing a program in C++ and I use a struct definition named Contact.
In a function in my program that returns an item of type Contact,i face the problem below:
Contact getContact(){
Contact c;
//do things
if(condition)
//assign c
else
//c is not assigned
return c;
}
So when it goes in else statement,the c remains unassigned,and the return c gives an error of course.
Is there a way to assign it with something like null so the return statement wouldn't face a problem?
Contact is just a simple struct.
Can anyone help me with how to work on Eclipse C++ IDE? I need a clear set of instructions on how to connect server and database as well as how to compile and run standalone codes?
I'm trying to convert My Console classes to .Net classes because I can't use std::vector or anything like that in WindowsFormsApplications. So I decided to convert all Vectors to Lists and I thought that the classes work the same but my code below throws a massive amount of errors and I have no clue why.. It's quite short and simple to read.
using namespace System;
using namespace System::Collections::Generic;
template <typename T>
public ref class CustomType
{
private:
List<T> TypeData;
public:
CustomType() {}
CustomType(...array<T^> ^Types) //Basically Variadic Templates.. As good as it gets for MS2010..
{
for each (T^ o in Types)
TypeData.Add(o);
}
~CustomType() {}
int size() {return TypeData.size();}
CustomType& operator [](int I)
{
assert(I >= 0 && !TypeData.empty());
return TypeData[I];
}
const CustomType& operator [](int I) const
{
assert(I >= 0 && !TypeData.empty());
return TypeData[I];
}
operator const List<T>& () const
{
return TypeData;
}
bool operator == (const CustomType &CT) const
{
return (TypeData == CT.TypeData);
}
};
But that does not work at all.. It's basically supposed to add Meh to the list within the class and I can access it at anytime to get the data.
Please help me. How do I overload in .Net and what is that Shevron? The ^ operator? I read that it's top level but have no clue what I read because I understood very little. Does ^ Replace the & operator?
I've been looking to figure out what a USB port does when it's overloaded by too much bandwidth (?), and it the port just shuts down, right? Might you have any ideas on where to look/what to look for with USB research? Is it even possible to automatically have a USB driver reset itself? Sorry if these are vague questions.
I'm creating the a Card game c++ program and I got some problem. PLZ help!!
I got few files:
Main.cpp (ask user which card game he want to play)
Card.h (creat rank and suit for cards)
War.h, War.cpp (creats War game)
TicTacToe.h, TicTacToe.cpp (creats TicTacToe game)
Game.h, Game.cpp (required to have a virtual function play() that all of the games inherit. Requires to use polymorphism to allow a single variable of type *Game() to access and play any of your games.
Here is my Main.cpp:
int main()
{
int response =0;
Game *myGame;
while(response !=3)
{
cout<<"Press 1 to play War\n";
cout<<"press 2 to play TicTacToe\n";
cout<<"press 3 to quit\n";
cin>>response;
switch(response)
{
case 1:myGame = new War();
break;
case 2:myGame = new TicTacToe();
break;
default:return 0;
}
myGame->play();
}
delete myGame;
}
First question: Since I use 'new' operator to create War or TicTacToe. When I build it, it said 'can not convert TicTacToe* to Game* in assignment. What's wrong with that?
Here is my virtual function play() in Game.h:(nothing in there, Idk if I'm wrong)
virtual void play(){};
and I have no idea the construction of each War and TicTacToe should look like.
So here is my code:
Card.h
class Card
{
private:
int rank; //the number on the card
//jack=11; queen=12; king=13; ace=14
CardSuit suit; //the suit of the card
public:
Card(int r, CardSuit s);//constructor
int getRank() const; //returns the card's rank
void setRank(int);
void setSuit(int);
void display(); //displays the card to cout
//e.g. if rank=11 and suit=HEARTS
//display Jh
};
Card::Card(int r, CardSuit s)
{
rank=r;
suit=s;
}
War.h and constructor:
class War: public Game
{
public:
War();
~War();
void play();
private:
Card *hc;
Card *cc;
};
War::War() //constructor
{
hc = new Card(2,HEARTS);
cc = new Card(2,HEARTS);
}
Here is TicTacToe.h (it dosen't need to use Card class):
class TicTacToe
{
public:
TicTacToe();
virtual ~TicTacToe();
void printInstructions();
void initializeBoard(char*);
void displayBoard(char*);
char winner(char*);
bool isLegal(char*, int);
void humanMove(char*);
void computerMove(char *);
void announceWinner(char winner);
void play();
protected:
private:
//The Tic-Tac-Toe board - a 9 character array
//Each character can be an X, O, or a space
//The space represents an open space on the board
char * pb;
char response; //User's response
char turn; //keeps track of who's turn it is
};
TicTacToe::TicTacToe() //constructor
{
pb = new char[9];
}
Thanks for helping me debug! I really appreciate it!
I am downloading content from a web source using URLDownloadToFile winapi function
All is well, with that, the content is downloaded to the correct path.
My probems start when I try to read it, like below, the loop never exits.
myReadFile.open(sFile);
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
//code;
}
}
cout << "done" << endl; // is never displayed
It has been working before, the only thing which has changed is the content of the web source
and perhaps it's encoding.
Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home.
Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , Y). A house can be located at a grid point (R, S) if the sum of the distances between this point and each of the restaurants is as small as possible. Find the number of possible house locations in the city to help out chef build a home.
More than one restaurant can be located at the same point.
Houses and restaurants can be located at the same point.
Every house must have integer co-ordinates. In other words, R and S are integers.
The distance between two points (A,B) and (C,D) is |A-C| + |B-D|. Here |X| is the absolute function.
Input
First line in the input contains T, number of test cases.
First line of each test case contains N, number of restaurants.
Each of the next N lines contain two integers X and Y separated by a space.
T <= 100
N <= 10^3
-10^8 <= X <=10^8
-10^8 <= Y <=10^8
Output
The number of possible locations (grid points) where houses can be built.
Example
depth : 8bit
format : QImage::Format_Indexed8
image width : 450
image height : 375
bytes per scan line : 452
How to integrate QImage with the example provided by the boost::gil?
This would cause segmentation fault yet I don't know why.
The algorithm seems nothing wrong
Thanks for your help
2008 scandalz.net
You or I must yield up his life to Ahrimanes. I would rather it were
you. I should have no hesitation in sacrificing my own life to spare
yours, but we take stock next week, and it would not be fair on the
company.
-- J. Wellington Wells