----- CurlT ( MAIN GCC DEBUG DEBUG_FULL BLITZ WIN32 )
curl.cpp
C:\MyApps\CurlT\curl.cpp: In function 'void* getfile(std::string, char*)':
C:\MyApps\CurlT\curl.cpp:39: warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime
C:\MyApps\CurlT\curl.cpp: In function 'int main()':
C:\MyApps\CurlT\curl.cpp:57: warning: deprecated conversion from string constant to 'char*'
CurlT: 1 file(s) built in (0:01.68), 1688 msecs / file, duration = 1703 msecs, parallelization 0%
Linking...
C:\upp\out\MINGW.Debug.Debug_full\CurlT.exe (1324179 B) linked in (0:00.67)
OK. (0:02.40)
HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Hey everybody ,
I'am writing a very simple chat program (Client & Server) in C++ & QTNetwork libary.
I Have a static cast problem that i don't understand , here is my code :
"The program will grade a series of exams and then print a grade report for students in a course.
Input: An instructor has a class of students each of whom takes a multiple-choice exam with 10 questions. For each student in the class, there is one line in the input file. The line contains the answers that student gave for the exam. The input file named "grade_data.txt" will have the following format:
line 1: the key for the exam (e.g.)
bccbbadbca
lines 2-n:
a set of answers. You know you are done when you get to a line with no data.
Note: You will not know in advance how many exams you have to grade and you don't need to store the exam answers in your program.
Processing: The program is to read the input file and grade each exam and print out the score for that exam.
Output: Here is an example of how the output might appear. You will write the report to an output file named "grade_report.txt"
student 1 - 8
student 2 - 10
student 3 - 1
etc.
Final Report
------------
10 - 4
9 - 2
8 - 3
.
.
1 - 3
0 - 0
high score - 10
low score - 1
mean score - 6.25"
ive done a lot of it so far but i cant figure out how to do a few things. I cant figure out how to list how many people got question 1 right, question 2 right, etc. and im having trouble finding the highest/lowest/ and mean scores.
i didnt use any arrays on this project, and im not sure if it would be better to use an array for this kind of thing or if i can still make it work without any arrays.
this is the code i have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream infile("grade_data.txt");
string grades, key;
string t1;
int temp;
int main()
{
if (!infile)
{
cout << "Error opening file\n\n";
system("pause");
}
else
cout << "File Successfully Opened\n\n";
if (a1==b1)
results++;
if (a2==b2)
results++;
if (a3==b3)
results++;
if (a4==b4)
results++;
if (a5==b5)
results++;
if (a6==b6)
results++;
if (a7==b7)
results++;
if (a8==b8)
results++;
if (a9==b9)
results++;
if (a10==b10)
results++;
bool equals (Cell& cell)
{
return(x==cell.x && y == cell.y && z == cell.z);
}
void draw()
{
/*glFrontFace(GL_CW);
glBegin(GL_QUADS);
glColor4f(0.0, 1.0, 1.0, 0.7);
glVertex3f(x, y, z);
glVertex3f(x + width, y, z);
glVertex3f(x + width, y + height, z);
glVertex3f(x, y + height, z);
glColor4f(1.0, 0.0, 0.0, 0.7);
glVertex3f(x, y, z);
glVertex3f(x, y + height, z);
glVertex3f(x, y + height, z + depth);
glVertex3f(x, y, z + depth);
glColor4f(1.0, 1.0, 0.0, 0.7);
glVertex3f(x, y, z);
glVertex3f(x, y, z + depth);
glVertex3f(x + width, y, z + depth);
glVertex3f(x + width, y, z);
glColor4f(0.0, 1.0, 1.0, 0.7);
glVertex3f(x + width, y + height, z + depth);
glVertex3f(x + width, y, z + depth);
glVertex3f(x, y, z + depth);
glVertex3f(x, y + height, z + depth);
glColor4f(1.0, 0.0, 0.0, 0.7);
glVertex3f(x + width, y, z + depth);
glVertex3f(x + width, y + height, z + depth);
glVertex3f(x + width, y + height, z);
glVertex3f(x + width, y, z);
glColor4f(1.0, 1.0, 0.0, 0.7);
glVertex3f(x + width, y + height, z);
glVertex3f(x + width, y + height, z + depth);
glVertex3f(x, y + height, z + depth);
glVertex3f(x, y + height, z);
so im writing some video/image editing software and im stumped... not about the code so much cuz what im doing works fine .. im not convinced it is the most efficient use of my computer but it works.
okay so my question is im not sure how jpg's or .mov's any image or movie extension is packed a way... i realize that it is a combination of 3 bytes.... so for black 3 characters would all have ffffff..
my question is where do i go to learn how these bits are packed away so i can manipulate them... any standard that would be published... (preferrably something simple but unlikely)
Well, unlike C, C++ provides a concept of headers(not header files) and that these headers are something like a collection of names, which may mapped as header files by the compiler.
Can anyone please correct me if im wrong in my above understanding. Also please state the main difference between a namepace and a header.(since even a C++ header is a collection of names)
is it possible to create my own simple programming language in c++?
complete with the compiler,editor and the libraries..
just a basic model where i can write simple instructions,save it with my own extension
and run atleast a few simple algorithms..
i needed a variable size bit string. And since bitset provides several operations, i wanted to use it. But is it possible to make it a variable size one?
class TryBits {
private:
string s;
bitset<n> b; //now i need n = s.size().
};
I need to write a C++ code, where if theres a String called "hello" in the code each character should appear (character by character) on the mouse focus.
That means where ever i click my mouse (Even on an external program), and when the on focus sign appears the characters of "hello" should appear there.
I studies that theres a function in C++ called SendKeys but i am not sure if its that i should look for. Can some one tell me the keywords to google or if your'l know any example to start on, please tell me, because it would be very useful.
I'd like to know what the ASCII codes for the toggle keys of the keyboard. I want to make the mouse clicks do different thing when the Caps Lock, or Scroll Lock is pressed.
template <typename MatTypeOne, typename MatTypeTwo>
void funct(MatTypeOne& m1, MatTypeTwo& m2) {
//here I would need to check whether m1 and m2 are of the same "type",
//meaning that MatTypeOne is the same as MatTypeTwo
}
What is the way to check whether m1 and m2 belong to same/different types?
Thanks
I realize that there are plenty of tutorials on how to create a "Custom Win32 Title Bar." The problem is.. none of the tutorials I have found so far.. discusses how a person would be able to "drag" the replaced title bar.. as one would drag the "normal" title bar.
If you do not know what I mean by "custom" title bar.. it only means that I would like to remove the "initial" window title bar (..the bar upon which the window's title resides) and replace it with one that I drew myself. Not only would I like to replace the standard title bar however.. but I would like to learn how to be able to drag the window from MY custom title bar image.. as one would drag the screen with the standard title bar.
Also.. if it is possible.. I would like to replicate the functionality which the WS_THICKFRAME attribute provides to a window.. only on custom bitmaps.
Example: I want a user to be able to click on lines that I drew.... which would reuslt in the window being scaled.. (as would occur if a person scaled a window with the default window sides provided).
int Vote_Amount[6]={0};//set amunt of votes
int key=0;
cout << "Please vote nominee by enter the noimee number" << endl;
while((key=getch())!=0x27)
{
switch(key)
{
case '1':Vote_Amount[1]++;break;
case '2':Vote_Amount[2]++;break;
case '3':Vote_Amount[3]++;break;
case '4':Vote_Amount[4]++;break;
case '5':Vote_Amount[5]++;break;
}
for(int i=1;i<6;i++)
cout<< "Nominee No."<< i <<" won "<<Vote_Amount[i]<< " vote(s)"<<endl;
}
return 0;
}
can i use c++ libraries and the compiler to create my own interface?
i just want to use a different gui for it..
a new editor of sorts.if yes then how do i go by it?
thanks..
while(p !=NULL)
{
pre = p;
p = p->link;
delete pre; // When running for the second time, pre value becomes
// 0x602030 but when the statement executes , it doesn't
// cause a SIGABRT
}
}
int main()
{
Node* ints;
ints = new Node; // link a node
ints->link = new Node; // link another node
delete ints->link; // Delete the second node (value: 0x602030)
// If I run the above statement again in main, it will casue a SIGABRT
//signal with the following message. media/<My project location>/dist/
//debug/ cppapp: double free or corruption (fasttop): 0x0000000000602030 ***
destroy(ints);
return 0;
}
I'm using debug mode and if I run "delete ints->link" statement twice in main, gdb will say the program cause a SIGABRT, when it hits the second delete statement because I free the same memory twice. But this doesn't happen when I run destroy method like in the above code.
In other words, According to my knowledge I'm freeing the same memory twice in the above program. It should cause a SIGABRT signal, right? but it doesn't. I need to know whether it's my mistake(ie. understanding in a wrong way or code error) or something wrong with the compiler?
I'm using g++ 4.4.3, Netbeans IDE, Ubuntu 10.4, gdb. I used gdb to see where the pointers point.
Just a quick question, if string::npos represents the largest possible value for a string object, how can this value be -1 if it's an unsigned integer?
I know this value will change for different compilers, as string::npos on my compiler is set to 4,294,967,295 which makes sense but I don't understand how -1 can represent the largest value.
I have a problem when i am writing a content into a files as a binary format.I noticed, that it writes the content two times into the file.
Here is the code.
I have a design question which I have not been able to find a satisfactory answer for by searching.
Essentially, I have a class - Base - that contains a vector of pointers to another class - Node. However, I would like to be able extend both the Base and Node class. This will involve adding new variables and functions to the classes derived from Node, and utilising these additional functions in classes derived from Base.
I can think of a few ways to accomplish this, but am unsure which is the best from a design point of view, as they each have their flaws. It has led me to think that perhaps there is a different design altogether which can accomplish what I need more elegantly.
Here is some example code illustrating my problem:
virtual void MakeNodes()
{
for(int i = 0; i < 10; i++)
some_nodes.push_back( new Node(i) );
}
public:
Base()
{
Initialise();
}
void PrintNodes()
{
for(int i = 0; i < some_nodes.size(); i++)
{
std::cout << "Node " << i << ":" << std::endl;
some_nodes[i]->Print();
}
}
int AddValues()
{
int temp = 0;
for(int i = 0; i < some_nodes.size(); i++)
temp += some_nodes[i]->GetValue();
return temp;
}
};
class BetterBase
{
virtual void MakeNodes()
{
for(int i = 0; i < 10; i++)
some_nodes.push_back( new BetterNode(i, i/2) );
}
public:
BetterBase()
{
Initialise();
}
double AddBetterValues()
{
double temp = 0;
for(int i = 0; i < some_nodes.size(); i++)
temp += some_nodes[i]->GetBetterValue(); // THE PROBLEM LIES HERE.
return temp;
}
};
int main(void)
{
Base * b = new Base;
Base * better_b = new BetterBase;
// Output details about Nodes:
b->PrintNodes();
// Virtual function in BetterNode takes over and outputs additional Detail:
better_b->PrintNodes();
// Lets find out what the sum of the node values from b are:
int b_values = b->AddValues();
std::cout << b_values << std::endl;
// We *know* that better_b contains additional information. What is it?
double better_values = better_b->AddBetterValues();
std::cout << better_values << std::endl;
// But ofcourse, this compiles with an error, because AddBetterValues does not exist in Base class..
return 0;
}
So, My derived BetterNode class is naturally going to extend the base Node class, and will need new values and consequently new functions to access them, that are unknown to the base Node class. However, it will share the common base properties.
In addition, the derived BetterBase class wishes to implement these BetterNodes and utilise their additional functionality in performing what it does. It will fill its some_nodes vector with pointers to BetterNodes. It can therefore use all of its parent Base class functions, as the BetterNode is derived from the Node.
I have tried to illustrate this problem in the above code. I do not need to reimplement my Print function, as classes derived from Node can virtually overload the Print function, which saves me effort. This is good. However, My derived BetterBase class wants to make use of the extended functionality of BetterNode, in this example by implementing AddBetterValues(). It obviously cannot, as the vector some_nodes is pointers to the base Node class, which does not know about this function.
So, How can I pull this off?
I have thought of a few ways, but am unsure which is best:
1. Make the Base class a template class, whereby I select which type of Node the vector some_nodes will hold.
example:
template<class T = Node> Base
{
protected:
vector<T*> some_nodes;
//...other code.
};
class BetterBase: public Base<BetterNode>
{
// now, AddBetterValues would work, as the vector is not of base class Node, but of BetterNode.
}
The problem here is that it allows for mistakes to be made. What if I derive from the Base class like this:
class AnotherBase: public Base<NonNodeClass>
Templating allows me to fill that vector with anything, not just classes derived from Node, which could screw things up. As such, this seems like a sloppy and potentially error-prone workaround.
2. Whenever I add functions to classes derived from Node, I can also prototype/define these functions as virtual in the base Node class. Now, the base class knows about additional functions, and there are no issues,
However, this seems like bad design practise, and people who derive from my classes should not need to go back and add relevant code into my base Node class. In addition, bulking out the base Node class with functions it does not itself need is just stupid.
3. Casting in derived classes. If, knowing that I will be using BetterNodes in the BetterBase class, I simply cast from Node* to BetterNode* when necessary, I would provide the additional BetterBase functions access to the required additional BetterNode functions. The downside to this approach is the requirement for an increasing amount of casting as the class derived from Node grows more complex, which seems sloppy. Also, people tend to say that this is a sign of a design flaw. As it seems like the simplest way to overcome my problem, does this mean that there is a better way I could structure my code?
So, which method is best? Or, do I need to think about redesigning my code entirely?
Can some1 giv me some clues to cont the deal card to players part ??? The program will deal cards once the user enter the numbers of player between 3-7, either five cards per player or seven cards per player depending upon the menu selection, to the players at the table. The dealer, the program, always is dealt to last.
void GenerateRandom (card *ptrCard, int arraySize);
void Display (card *ptrCard, int arraySize);
void dealCard (card *ptrCard, int pNum, int cardSize);
void GenerateRandom (card *ptrCard, int arraySize){
// this method will generate repeated random numbers. boolean array
// keeps track of what numbers have been picked. Generates another if
// this number has already been picked.
bool* picked = new bool[52];
// initialize 52 cards to unpicked
for (int i = 0; i < 52; i++)
picked[i] = false;
int value;
//assumes all the generated cards are different in location for every new game
for (int i = 0; i < arraySize; i++)
{
value = rand () % 52;
if (!picked[value])
{
ptrCard[i].rank = value;
ptrCard[i].suit = value; // card hasn't been picked then assign into array,
picked[value] = true; // flag as picked.
}
else
i--; // already picked.
}
delete [] picked;
}
void Display (card *ptrCard, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout <<right << setw( 3 ) <<i + 1<< ". "<< right << setw( 5 ) << wRank[ptrCard[i].rank % 13] << " of "
<< left << setw( 8 ) <<wSuit[ptrCard[i].suit % 4]<< ( (i + 1) % 2 ? '\t' : '\n' ) ;
}
}
void dealCard (card *ptrCard, int pNum, int cardSize)
{
do{
cout<<"Enter the players Number: "<<flush;
cin>>pNum;
}while (pNum < 3 || pNum > 7);
int cardRange = pNum * cardSize;
int *player = new int[pNum];
/****************
for (i=0; i<pNum ; i++)
{ ***HOW TO PASS GENERATED RANDOM CARDS TO THE PLAYERS ???
I already know how to create a program using just one window.. but I'm having trouble creating a program with 2 windows.
I used CreateWindow() to create my second window, however, my second window displays exactly what is on my main window!
I figured the reason was because my WinProc function was handling messages for all windows (including the second window), and so on WM_PAINT, everything intended to be painted on the main window.. also gets displayed on the second window as well.
What I would like to know is how I would get my second window to have its window messages handled by a SEPERATE handling function (aside from WinProc).
Note: I've already managed to create a second WndProc function, the problem is.. I do not know how to set my second window.. to USE that second WndProc function. Even though there is a second WndProc function created.. my second window still utilizes the first WndProc function for all of its window messages!
Hello Everyone ,
I'am new to OOP and QT and i'm trying to write a simple chat program (client , server) with winsockets.
I Have an error which i don't seem to understand :
this is my code so far :
#include "pmessenger.h"
#include "ui_pmessenger.h"
#include <QMessageBox>
#include <winsock2.h>
SOCKET s;
PMessenger::PMessenger(QWidget *parent) : QMainWindow(parent), ui(new Ui::PMessenger)
{
ui->setupUi(this);
WSADATA wsadata;
if(WSAStartup(MAKEWORD(2,2),&wsadata)!=0)
{
QMessageBox::critical(this,"Error","Winsock Startup Failed",0,0);
this->close();
}
s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
QMessageBox::critical(this,"Error","Socket Creation Faild",0,0);
WSACleanup();
this->close();
}
SOCKADDR_IN server;
server.sin_family = AF_INET;
server.sin_port = htons(7676);
server.sin_addr.s_addr = inet_addr("my ip is here :D");
if(::connect(s,(sockaddr*)&server,sizeof(server))!=0)
{
QMessageBox::critical(this,"Error","Can't Connect",0,0);
WSACleanup();
this->close();
}
CreateThread(NULL,0,ServerMsgThread,(LPVOID)s,0,0); // the problem is in this line :(
}
Ok, so I'm writing a program to convert decimal into binary. It all works with the exception that my binary shows up in reverse order and I'm having trouble with reversing the array of chars in my intToBinaryString() function.
Any tips on how to get this started?
#include<iostream>
#include<cstring>
using namespace std;
void intToBinaryString(long int, char []);
#define ARRAY_SIZE 10001
int main()
{
long int number;
char binary[ARRAY_SIZE];
int count = 0;
cout << "Enter a non-negative integer to convert to binary: ";
cin >> number;
if(number >= 0)
{
cout << "The binary representation for " << number << " is: ";
intToBinaryString(number, binary);
}
else
cout << "Enter a non-negative number" << endl;
cout << endl << endl;
system ("pause");
return 0;
}
void intToBinaryString(long int num, char bin[]) //NOTE:check pg 817 for c-string info
{
int remainder, n=0;
char tempArray[ARRAY_SIZE];
do
{
remainder = num%2;
num = num/2;
itoa(remainder, tempArray, 10);
cout << tempArray;
}while(num > 0);
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows;
cout<< "put the number of rows here"" ";
cin >> rows;
cout<< "numbers here""\n ";
int *arr = new int[ rows ];
for( int i = 0; i < rows; i++ ){
cin >> arr[ i ];
}
cout endl;
int col;
cout<< "put the number of columns here"" ";
cin >> col;
cout<< "numbers here""\n ";
int *arra = new int[ col ];
for( int j = 0;j < col; j++ ){
cin >> arra[ j ];
}
return 0;
}
i want to have a multiplication table after this commands...how can i?? ove try it all
I have a situation whereby I need to copy the contents of an STL vector into a memory buffer provided by the system. One might think that given:
std::vector<ObjectType> source; // Initalized to hold the objects
ObjectType* target = reinterpret_cast<ObjectType*>(buffer); // Points to system provided memory buffer
someone could do the following:
std::copy(source.begin(), source.end(), target);
This can be problematic, however, because ObjectType is a complex class whose instances contain instances of other classes. The memory buffer from the system is raw memory which does not have properly constructed objects in it, so the copy algorithm would be performing an assignment to an improperly constructed ObjectTypes.
One way to work around this would be something like the following:
This technique uses placement new and the copy constructor to create copies of the items from the vector into the memory buffer. This will work as ObjectType does have a valid, public copy constructor.
I'm wondering if a more elegant solution can be developed that can still allow the use of the std::copy algorithm to accomplish this task. Perhaps someone could use an object similar to std::inserter and can be used on an array, like maybe some sort of replacer object that does the job of the placement new operator in the above loop when called in something like the copy algorithm.
I'm wondering if such an object already exists, that someone can make use of. If something doesn't exist, I'm wondering how practical it would be to create such a thing.
Also, perhaps there is another way to solve the problem that doesn't involve anything suggested so far.
basePtr = &someBase; //set base obj pointer to base obj
basePtr->nVirt(); //as expected
basePtr->yVirt(); //as expected
basePtr = &someDerived; //set bas obj pointer to derived obj
basePtr->nVirt(); //????
/*
why does a pointer of base type still call base methods when it is
pointing to the address of a derived obj? do base obj pointers
always point to base methods even when pointing to derived obj's?
*/
basePtr->yVirt(); //????
/*
why should i be surprised that same pointer is calling the yvirt
function since it is pointing to a derived object? shouldn't a
pointer to a derived object also point to that object's members?
*/
derivedPtr = &someBase; //ERROR????
/*
i've read that a pointer to derived obj can point to a
base obj. why not here? what gives?
*/
return 0;
}
I want to do a simple music player, you know, the slider with the seconds you're on, play/pause, stop, open file, show recent files,about and exit. I tried QT's Phonon, but it isn't working, I get a lot of errors trying to compile the example code from qt's official website http://doc.trolltech.com/4.4/phonon-musicplayer.html and the code from the tutorial in the Phonon's official website Urlhttp://api.kde.org/4.0-api/kdelib...onon_tut1.html.
I wanted to know if anybody knows another library/framework on which I can do the music player, and that it doesnt take too long to learn. Im considering Windows programming, but it seems to be a little hard(at least harder than QT), or show me some code of an already made music player, for me to watch it and learn.
ive already run the installation wizard and why i always run the main setup the thing that comes out is this "a previous installation of visualsourcesafe at D:visual basic 6.0\VSS\ select yes to replace it with VSS6.0 or no to install and no to its default" 5then i encountered this one "you must first run the installation wizard before running this setup"
Hi there, I'm new to the forum so please be kind :)
I've created a class called node that has a standard constructor and an overload that uses an int as an argument.
class node
{
public:
node(void);
node(int inputs);
...
};
I can create an dynamic array of nodes with
node *nodes;
node = new nodes[number];
which works very nicely. But now I want to setup the nodes using the overloaded constructor. I tried
node = new nodes(width)[number];
but that just created a whole load of errors. I realise I could make another function in the node class that could make the changes the overload would've done but I want this to be as neat as possible. Any help would be greatly appreciated.
Thank you, Tom
Can anybody tell me that how can i open file and write it in winform C++? i have googled alot and searched msdn but could not find appropriate help. I also tried using fstream's objects but they were declared unidentified on winform. what can i just do? what stream class should i use? please also specify its header file.
I have been programming for a while, currently a junior CS student. Programming has always felt very natural to me and I pick up new concepts quickly and I generally retain most of what I learn. However, when it comes to converting between Dec/Bin/Hex as well as performing bitwise operations, I have never really been able to retain the process. Also, the problem is that every programming book that I have accumulated over the years always seems to only touch on the subject lightly, like a quick review. I am looking to find some good, in depth and intuitive reading about converting between the three and also mastering bitwise operations. I know this is something that is covered in basic courses but for some reason I have never been able to really master it.
I am currently working analysising silicon pixel detectors for the LHC at my university.
One thing i have to do is to find clusters of signal in a silicon pixel detector.
I have directory of macros which handles the data and getting it ready, not important.
My goals are to create a macro/ algorithym that finds clusters of data, with this i want to:
1) find number of 1 cluster hits, 2 cluster, 3 cluster etc.... on the sensor
2) this info will be made into a histo (not a problem)
3) histo's of 1 cluster, 2 cluster and 3 or more clusters will be filled with the total relevant signal
background:
The sensors i used are silicon pixel, they are very small and are designed for charge sharing, this means that pixels are prone to share there charge with surrounding pixels. this allows for a good resolution.
The sensor is made up of 2048 pixels sensors with 256 read out channels. therefore each channel is attached to 8 pixels. the pixels aren't next to each other they6 are spread out over the sensor in a specific pattern.
pixels connected to channel 1 and 2 arnt next to each other either.
i used a 2D array as a model of the sensor layout. were each element can be thought of as a pixel. each element in the array is filled with the relevant channel for that "pixel"
vectors havnt been used to simpilfy things since a spacial position isnt required merely a position with refference to the other pixels.
The 2D array has the form PIXEL[16][128]
where the signal for each channel is _signal[256]
any help about how to find the clusters is much apreiated
Hi,
I'm trying to develop application with separation of UI/BL/DAL.
I have read a lot of theories and I'm trying to develop a blue print for my application.
I have no problem in UI thing. But I have problem with designing Data Access Layer.
It will basically be a SQLite database backend (I may add other backends as well as XML).
Now I don't know how to write class(es) to do the DAL. So please help me get on it, perhaps with very simple example.
hey folks, i have a problem which seems to be reasonably simple but i havnt managed to figure it out yet. Iv read alot of the other threads on this but i still havnt found one that iv both understood and solved my problem. So here goes...
Its concerning returning a member variable, that is a 2d array made within a class, to the program.
//located in the class header file
int** m_iPopulation;
//located in the class constructor
m_iPopulation = new int* [m_iPopDensity];
for(unsigned short int i=0; i<m_iPopDensity; i++)
m_iPopulation[i] = new int [m_iChromeLength + 4];
the above all works fine, i can see the population when i fill the array and i can print them to the screen etc. The problem comes when i try to return the above array to the main program.
//located in class header file
inline int** GetPopulation(){return m_iPopulation;};
//located in the main() program
int** iPopulation = new int* [iPopDensity];
for(unsigned short int i=0; i<iPopDensity; i++)
iPopulation[i] = new int [iChromeLength + 4];
iPopulation = _pGA->GetPopulation();
when i try to print whats in the array all i get is 1 memory address. and when i debug all i can see is a single entry in the array.
not sure what im doing wrong and i cant find anything else on the fora to help me, so any help is greatly appriciated.
//i am writing a code that read from a file and store words in an character array but //in the wriiten by me,it is compiling but not extracting words in the array.
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;
int main()
{
ifstream fin;
char ch;
int j=0;
string line;
//reading from file.....
fin.open("rajkamal");//rajkamal is a valid file.
while(fin)
{
getline(fin,line);
}
cout<<"\n"<<line;
fin.close();
//putting data into an array from a string.
cout<<"\n"<<line;
char *a=&line[0];
cout<<endl;
cout<<a<<"******"<<endl;
cout<<a[0]<<a[1]<<a[2]<<a[3]<<endl;
Guys, could someone help me to make a program that will display this not using if-else statement.
I want to learn how to make it using for loop statement and any statement that will make this program short. I need 1 Program using for loop and another program but not if-else.
I cannot predefine a structure because I dont know what data types I am gonna be given.How can I store the records? I was thinking of declaring a multidimensional double array and typecasting all the records and then casting back whenever necessary. Does this seem sensible? Is there a better solution?
Hi, i'm supposed to write a function, countGrade that takes in the Grade and find the number of students that have this grade. This value is returned to the calling program. The function prototype is int countGrade(char). Currently all i have written is this.
Seem like there's something wrong with my function but i have no idea how to fix it. Any help would be appreciated. Thanks in advance!
#include <iostream>
#include <string>
using namespace std;
this is a part of the whole code for simulator of 8051 . when i compile it , it compiles successfully with DEVC++ ide, but at the run time it shows inifinite times or the "Error:hex file error" . I cant understand how to solve this . I want your help to solve this . plz help me soon.Thank you .
This program will calculate new price for the type of cars after being taxed.
This program will display type of car, package and the price that has to paid by the customer.
This program will continue until user request to stop.
At the end; the program will display:
-number of customer for CAR1 type
-number of customer for CAR2 type
-total sales for CAR1 type
-total sales for CAR2 type
-total sales for all cars
Let me preface this by saying that I am a computer science student with only a rudimentary introduction to C++ so far, having worked mainly in Java up until now. I apologize if this is an overly simplistic question.
A relative of mine has asked me to program a visual timer for them. I could probably do it in Java but I figured giving it a shot in C++ would let me practice a bit. Anyways, I am not even sure where to start insofar as graphics go.
The idea behind the timer is that the user is able to input a time (of course) and the clock will tick down in front of a circle that fills up in a pie-like manner (if that makes any sense at all!). I think that this is the basic idea for the circle animation: http://download.cnet.com/VitalSmarts...-10990391.html (The rest of it would be different, of course, that's just a reference for the circle and I'm not making it for commercial use.)
As I said, I've only done graphics and animation in Java, so I am at a total loss as to what I could research. I'm aware of OpenGL for graphics but I don't know if this would be overkill, if there is something better suited, etc. Any point in the right direction would be greatly appreciated.
The insruction is create a program that asks for two input srings until the character 'x' is encountered. For each input string display as output its length, its reverse and the concatenation of reversed inputs (see output below).
Sample output:
Enter 1: Hellox
enter 2: Goodbyex
the inputs are: Hello and goodbye
the lengths are: 5 and 7
the reverse are: Olleh and eybdoog
concatenation: Olleheybdoog
I'm having trouble even getting started with this problem. I've tried looking at other examples, but I'm completely stuck.
The question and my code(not even sure if im on the right track) is as follows:
Write a function called decToBinaryString that recieves a non-negative int and returns a string that is a binary representation of the number input.
tips - concatenate strings together
test odd/even using %
write a main() that test the code
#include<iostream>
using namespace std;
void intToBinaryString(unsigned long int, char *);
#define ARRAY_SIZE 1000
int main()
{
unsigned long int number;
char binary[ARRAY_SIZE];
int i;
cout << "Enter a non-negative integer to convert to binary: ";
cin >> number;
intToBinaryString(number, binary);
cout << "Binary representation: ";
for(i = 0; i < binary
system ("pause");
return 0;
}
void intToBinaryString(unsigned long int num, char *bin)
{
int remainder;
if(num%2 == 0) //even
{
do
{
remainder = num%2;
}while(num > 0);
You are to write a program that plays the game of “Guess the Number”. Your program is to randomly choose a three-digit number, allow the user to guess, provide feedback indicating if the users’ guess was too high or too low, and count the number of guesses the player makes.
Your program should provide and make use of functions:
void secretNum (int& num)
Determines the secret number to be used, passing back by reference parameter.
bool checkGuess(int guess, int answer)
This function returns true if ‘guess’ is equal to ‘answer’, and false otherwise.
void guessResponse(int guess, int answer)
This function prints a message indicating if the ‘guess’ is lower or higher than the ‘answer’
void countResponse(int count)
If count is less than 10, this function prints “You must know the secret”.
If count is equal to 10, this function prints “You got lucky”.
If count is greater than 10, this function prints “You should be able to do better than that”.
Your main function will:
Determine the secret number (use the stdlib function rand for this)
Ask the user to guess
If the user did not guess correctly
Provide feedback for the guess
Repeat the above until the user guesses correctly
Output the guess count and feedback indicating how the user did
This should be repeated for 10 problems. Prior to exiting, the program should print the lowest and highest number of guesses that occurred.
* Constant variables should be provided to store any number, which would appear in the code so that these can be easily changed if, need be.
Below is what i have so far. I am getting an error when i tried to compile it. I don't know where I have made an error. I would really appreciate it if someone could help me point out what I am doing wrong.
// Pro2a.cpp : Defines the entry point for the console application.
//
i am to write a C++ program to output the binary (base – 2) representation of a decimal integer. the program should accept a positive integer from the user. After verifying that the input is valid, the program should call a function named toBin, which outputs the binary representation of the number.
The function toBin must not be a recursive function.
I am a beginner in C++.I don't know where to start and don't really understand the question. It would be really helpful if someone could show me an example of what i am supposed to do. Thank you.
Hey
I've only been coding for a couple of days
and I got this code im working on
for some reason the computer only guesses the number 42 instead of a random number
can someone help me?
Heres the code:
/*========================================================================\
|This is basically the guess my number game |
|But the roles are reversed, well I'm going to try it anyway |
|-------------------------------------------------------------------------|
|31/08/2010 - 9:00 started |
|31/08/2010 - 9:51 finished |
|Its slightly flawed as in the random generator only sticks to one number |
|once I learn another method I will update this script |
|-------------------------------------------------------------------------|
|By Chris Forgeard |
|Copyrighted 31/08/2010 |
\========================================================================*/
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
//first ill set up the random number generator etc.
int number = rand() % 100 + 1;
int tries = 0;
char right = 'n';
cout << "Welcome HP MINI, guess my number!" << endl;
//The game loop
while (right == 'n')
{
cout << "Is it " << number << "?" << endl;
cout << "(y/n)" << endl;
cin >> right;
if (right == 'y')
cout << "Yes HP MINI, that is right!" << endl;
if (right == 'n')
cout << "Sorry HP MINI, that is wrong!";
++tries;
}
//The end scene
cout << "Congratulations HP MINI!" << endl;
cout << "You did it in " << tries << " tries!";
cin >> right;
Hi, I'm having some problems with this bit of code. I need to randomly open some files that have numbers as their filenames. i came up with this snippet to be able to open them from numbers 0 to 99. The code should randomly pick a number and try to open a file with that name, if the file does not exist, it lowers the range of numbers it can pick until reaching 10. I ran this on Ubuntu and it worked perfectly, but when I switch to Windows the loop never ends. If instead of using a random filename I use, for example filename="Synthesis//2.txt"; the program runs fine. i don't know why the code works on Ubuntu but not in Windows Vista. Any help is apreciated.
std::string Synthesis::itoa(int number)
{
std::stringstream word;
std::string output;
word<<number;
word>>output;
return output;
}
int Synthesis::Load( int Level){
int disponible=100; // las sintesis disponibles del 0 al 99 en ese level
ifstream tempsynth;
string filename;
int SynthNumber;
do {
SynthNumber = rand() % (disponible)+ Level*100;
filename="Synthesis//"+itoa(SynthNumber)+".txt"; //itoa is a custom funtion that return a string
Log<<filename.c_str()<<"\n"; //this prints the filename into a file
tempsynth.open(filename.c_str());//,ios::binary);
if (!tempsynth && disponible>=10)
disponible=disponible-3; //como no van a haber 100 sintesis se baja la busqueda hasta que hallan
}
Here is my code
excuse me if it seems a bit off
i've only been coding for a day :)
What I want it to do is in the comments at the top
/*======================================================================
IN THIS PROGRAM I WILL TRY AND SCRIPT A CONVENTIONAL CALCULATOR
WITH THE USER ENTERING THE NUMBERS THEY WISH TO MULTIPLY ADD ECT.
ALSO I WILL MAKE A CANCEL FUNCTION WHICH ERASES OR LOOPS THE PROGRAM.
JUST TO CLARIFY THIS PROGRAM IS COMPLETELY MADE UP AND WAS MADE BY ME
WITH NO HELP WHATSOEVER.
------------------------------------------------------------------------
31/08/2010 13:00 - STARTED
31/08/2010 15:28 - FINISHED
HAS SOME FLAWS IF YOU TYPE 'C' INTO WHERE IT ASKS FOR A NUMBER IT GOES CRAZY.
ALSO SOME FUNCTIONS ARE NOT COMPLETE SUCH AS THE CANCEL FUNCTION, I WANT
IT TO CLOSE THE PROGRAM WHEN 'C' IS PRESSED.
ALSO THE FUGTURE MODULUS FUNCTION IS YET TO BE CREATED.
------------------------------------------------------------------------
31/08/2010 - 16:24 STARTED
31/08/2010 - 16:34 FINISHED
STILL CAN'T GET FUNCTIONS TO WORK SUCH AS MODULUS AND CANCEL.
------------------------------------------------------------------------
BY CHRIS FORGEARD
========================================================================*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//I CHOSE DOUBLES JUST INCASE USER CHOOSES TO USE DECIMAL PLACES
double number;
double number_2;
char cancel = 'c';
double result_times;
double result_add;
double result_minus;
double result_divide;
int main()
{
cout << "Welcome to the calculator!\n" << endl;
//=====================================================================
//THE CALCULATOR LOOP
while (cancel == cancel)
{
cout << "Please begin by entering your first number\n" << endl;
cin >> number;
cout << "Now enter your second number please\n" << endl;
cin >> number_2;
//---------------------------------------------------------------------
//OPTIONS
cout << "Now what would you like to do?\n" << endl;
cout << "1: multiply" << endl;
cout << "2: addition" << endl;
cout << "3: minus" << endl;
cout << "4: divide"<< endl;
cout << "5: cancel" << endl;
cout << "6: coming soon (modulus)\n" << endl;
//---------------------------------------------------------------------
//SETTING UP CHOICES
int choice;
cout << "\n\nChoice: ";
cin >> choice;
//---------------------------------------------------------------------
//THE SWITCH PROGRAM (DEPENDS ON CHOICE WHAT PATH PROGRAM TAKES)
switch (choice)
{
case 1:
cout << "You have chose to multiply your numbers" << endl;
result_times = number * number_2;
cout << "Your answer is: " << result_times << endl;
break;
case 2:
cout << "You have chose to add your numbers" << endl;
result_add = number + number_2;
cout << "Your answer is: " << result_add << endl;
break;
case 3:
cout << "You have chose to take away your numbers" << endl;
result_minus = number - number_2;
cout << "Your answer is: " << result_minus << endl;
break;
case 4:
cout << "You have chose to divide your numbers" << endl;
result_divide = number / number_2;
cout << "Your answer is: " << result_divide << endl;
break;
case 5:
cout << "You have chose to cancel!" << endl;
break;
default:
cout << "I'm sorry but that option is not available!" << endl;
break;
}
}
//END OF LOOP
//================================================================================
Hi Guys, I'm wondering if someone can help me out with a problem I've been having with VC++. I'm obviously just beginning to learn C++ and have been working with CodeBlocks and VC++ 2010 Express. My problem is that the following code compiles in CodeBlocks but gives me numerous errors and dies with VC++ (for the sake of space, I've simplified it as much as I can down to the problem area)...
#pragma once
#include <iostream>
using namespace std;
string strFunction(int x);
Since I'm only dealing with two source files and a miniscule program, obviously a header here isnt really necessary, but I really want to learn how to work with them for later use. The maddening thing about this is:
1) The header works for some things. I use it to #include <iostream> without any trouble, I can declare global variables just fine, etc. Its really just something with any function prototypes I put in there.
2) Function prototypes work fine if I just manually copy the prototype into the other source file. I only get the errors when I reference it in the header.
Here is (a small part) of the errors I receive when I try and run the above project:
Main.cpp
1>c:\users\michael\documents\visual studio 2010\projects\project7\project7\main.cpp(5): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(726): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\ostream(764): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
----
I'd be tremendously appreciative of any help you guys could offer me. I've tried everything I could think of and experimented with everything I can think of but nothing seems to work. FWIW, I've tried this code in a completely empty VC++ project as well as inputting it into their custom made console app. Same errors.
trying to write a fuction to work out the GCD of two numbers
seems to run ok but the return is incorrect
any help much appreciated
#include <iostream>
#include <cmath>
using namespace std;
int g_c_d(int a,int b);
int main()
{
cout<<g_c_d(2871,4060);/*test example*/
cout<<endl;
system("pause");/*been advised not to use this but at my level well hey!*/
return 0;
}
int g_c_d(int a,int b)
{
int c;
c=abs(b-a);
cout<<a<<" "<<b<<" "<<c<<endl;/*put this in to check it was going ok*/
if(c==0){return a;}
if(b>a){b=a;}
a=c;
g_c_d(a,b);
}
returns 4249024 instead of 29
sorry this may be double post just new to this
didnt know wether it should be code snippet or discussion thread
Hey there,
this code was supposed to work out th GCD of 2 numbers
added cout line in function and code seems to be running fine
but it returns 4249024 instead of 29
this is probably a basic error on my part but can anyone tell me why?
thanks for any help
as is quite clear am a beginner at this.
I have a problem when i am writing into files in a binary format.I have noticed that, it writes two times into the file. Here i have attached the code.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class bank
{
protected:
char receive[20];
public:
}
I can't decide what data structure to use for a program I'm making.
the program I'm making is a football table, the variables used so far are;
string team;
int played = 0, goalsfor = 0, goalsagainst = 0, goaldiff = 0, win = 0, draw = 0, lose = 0, points = 0;
I was originally thinking of using a vector as I can resize it when I set it up. the table is organised by the points initialy and in the event of a tie goal difference is used.
I have recently stumbled upon a program that permits a person to have an animated image "dance" across the users' current active window. The problem is.. something very strange occurs when I have this animated image dancing across MY program's main window.
For some reason, whenever I either maximize or minimize MY program's main window (while this animated image is dancing across my screen), whatever frame within the images' animation sequence that happened to be playing when I maximized/minimized my screen, gets "imprinted" on MY main program's window.
Ex:
If the animated image happened to be jumping when I maximized my window.. a jumping character would be imprinted on my main window's screen (wherever that image was jumping at at the time of the window's maximization).
The problem is.. the "imprinted" image.. does NOT go away on my main window's screen!
In order to get rid of that imprinted image.. I've tried Invalidating my window's entire screen on window maximization (which works some of the time) but some times.. the screen invalidation does NOT get rid of the imprinted image.
The only method I've found that actually gets rid of the imprinted image EVERY time.. is to drag my program's window off screen.. and pull it back on the desktop again.. which does an automatic screen invalidation, and repaints everything on the screen when the window becomes visible again.
My question is.. WHY isn't a simple screen invalidation getting rid of the imprinted image every time I force a screen invalidation?
Please Note: Yes, I am sure the screen is being invalidated when it is supposed to be, as the entire screen "flickers" on screen invalidation. (But the imprinted image is still there!)
Hello!!
Can u all tell me what are different types of apps......lyk console apps,win32 apps etc.....what is basic difference between win32 n console apps.............. THANKS IN ADVANCE!!:)
I need to take a class on using C++ Libraries.
Something that's about 3 months in duration, with some sort of a test at the end.
I could easily just go to google and start there, but I was afraid that I would just get a zillion classes, without any way of knowing what is "shinola" and what is s***thing else.
Any suggestions for high quality, online learning that fills this bill would be greatly appreciated.
I am writing code for a guessing game program. The game is supposed to generate a random number, 3 digit number and let the user guess what it is, providing feedback for every wrong input. It is also supposed to perform 10 iterations, keeping track of the number of guesses. It then should use this record to determine the fewest guesses it took to figure out the number. I have the program set to execute 2 iterations for ease of troubleshooting. It also provides the secret number generated for reference.
I have been having trouble implementing a method of logging the number of guesses it took per random number generated. I tried a function tied to int &count inside of guessCollector( ) and a few permutations of. All I can manage is to get the code to output the number of guesses during the last iteration of the game. What would be the best way to go about this? Any ideas are greatly appreciated. I've considered using an array, but have not tried tom implement one yet. We are not allowed to use global variables.
#include <iostream>
#include <time.h>
using namespace std;
void secretNum(int &answer);
//function to generate a random number from seed
bool checkGuess(int guess, int answer);
//used to check operator's guess
void guessResponse(int guess, int answer, int count);
//provides feed back to the user; tells whether guess is too high or low
void guessCritique(int count);
//rates user based on number of guesses
void guessCollector(int &guess, int &count, int answer);
//collects guess from user
int tracker(int count);
//score keeper
void returners();
//function to repeat the sequence of functions 10 times, and count the fewest number of guesses.
int main ()
{
srand(time(0));
returners();
return 0;
}
void secretNum(int &answer)
{
int num = rand()%899+100;
answer = num;
}
void guessCritique(int count)
{
if (count < 10)
cout << "You must know the secret\n";
if (count == 10)
cout << "You got lucky\n";
if (count > 10)
cout << "You should be able to do better than that\n";
cout << endl;
}
void guessCollector(int &guess, int &count, int answer)
{
count = 0;
int input;
do {
cin >> input;
count++;
guess = input;
guessResponse(guess,answer,count);
} while (!checkGuess(guess,answer));
}
int tracker(int count)
{ int placeh, tracked = 10;
placeh = count;
if (placeh < tracked)
{
placeh = count;
}
return placeh;
}
void returners()
{
int answer, guess, count;
int tally = 1;
for (tally <= 2; tally <= 2; tally++) //change to 10
{
secretNum(answer);
cout << answer << endl; //DELETE. used during runtime to check random number
I have two classes and one of them is inherited from the other class.
Class Person - used to store first name and last name of a person. The data members are protected.
Class Candidate - used to store votes of an election, and this is inherited from Person class so that I can store name of the candiadate.
I have overloaded these operators in Person class : ==, !=, <, <=, >, >=
I have also overloaded the same operators in Candidate class too but the definision are same because you can only use the name of the candidate to compare. So rather than copy and paste the same code, I used static_cast. It worked but I wonder is it bad to do like that?
Ex:
bool Candidate::operator ==(const Candidate& right) const
{
//return (firstName == right.firstName && lastName == right.lastName);
// Rather than the above, I used this...
return (static_cast<Person>(*this) == static_cast<Person>(right));
}
Hey guys!!
i m a student.....n tryin 2 make a game in C++.....game is goin on very well but i hav a question.
i m using borland c++ 3.0 compiler....i hav 2 necessarily use this bcoz v hav d same compiler at high skool.....i'll start using d latest within few weeks.....but i hav to finish dis game within 1/2 a month.....i hav created 2 buttons named as "PAUSE" AND "RESUME"....
nw i need dat ....when i click these buttons....they must do d functions at tym of execution.....i.e if i click pause......the game or rather the execution must be PAUSED.....n if i resume.....the game(i.e execution) must start from where i paused......is there any system function to pause and resume...at tym of execution....if so plzzz let me kno....:-/.... THANKS IN ADVANCE!!
Hi, I have a problem which has been puzzling me for a few days. i have been trying it with vectors and characters but will not work for me. Imagine an "ON" "OFF" binary sequence. I want to compute all combinations of that sequence of length N say.
e.g sequence 001011 of length 6, but want all possibilities arising of length 6
I was thinking about using the <BITSET> class and defining for example
std::bitset<100>
Is this the best way for a sequence of "ON" "OFF" code? Then from here what is the best way to make sure all the possibilities of the sequence can be generated?
(( On a side note, I can't have for instance "std::bitset<N>" where N is user defined or defined elsewhere. The error is 'expression must have a constant value' so I think its something to do with address?))
Thanks for your time in reading if you have gotten this far.
Hey guys, I was wondering if any of you could help me with some stuff which may seem obvious to you but I'm a beginner.
I'm making a calculator and have reached the part where I am making the buttons change the string on the calculator's "screen".
The way I am doing this is by getting the current line of numbers as a string and then converting the number pressed into a string and then adding the two strings together to form the new calculator display, I then want to display that string.
After reading some books and looking online I thought the best way of doing this would be to use string streaming, so I have made the following:
I had problems setting the text as "TotalInputString" and got these compiler messages:
Quote:
error C2664: 'void System::Windows::Forms::Control::Text::set(System::String ^)' : cannot convert parameter 1 from 'std::string' to 'System::String ^'
1> No user-defined-conversion operator available, or
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Therefore I decided to change it by converting the TotalInput float to a string, which worked but the calculator would only allow me to input 7 numbers before showing "Infinite" on the calculator display and then any further input would result in the first number being a "1" despite pressing any of the buttons.
So my question is - how do I do this? All I want is for the string to allow me to place as many numbers as I need on the display. How do I change the text in such a way?
This was done on Visual C++, sorry if that's a problem.
I'm trying to find duplicates in an array and removing them by shifting the array index using the same array. I can't figure out where in my code the problem is but I'm still getting a duplicate. Could someone please help pinpoint the problem? I've tried debugging it but I'm not seeing it.
#include <iostream>
using namespace std;
int removeDuplicates(int A[], int n){
int last = n-1;
int found = 0;
//bool flag = false;
Can someone please compile this program and send me the screen shot of the output of this program? I can not compile on the current computer I am on, and all I need is the output screen shot. Thank you so much! It is an analog clock program.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
#include<dos.h>
int main()
{
struct time *t1;
int gdriver =DETECT,gmode;
initgraph(&gdriver,&gmode,"");
while(1)
{
gettime(t1);
circle(300,150,100);
printf("The current time is: %2d:%02d:%02d.%02d\n", t1->ti_hour,t1->ti_min,t1->ti_sec);
if ( (t1->ti_hour) >12) {t1->ti_hour=t1->ti_hour-12;}
setfillstyle(1,BLUE);
pieslice(300,150,(360-(t1->ti_hour*30))+90,(360-(t1->ti_hour*30))+95,40);
setfillstyle(1,RED);
pieslice(300,150,360-(t1->ti_min *6)+90,360-(t1->ti_min*6)+95,80);
pieslice(300,150,360-(t1->ti_sec *6)+90,360-(t1->ti_sec*6)+91,90);
sleep(1);
}
getch();
closegraph();
return 0;
}
I'm trying to send variables from a program in C++ to php for it to process.
Then I want to be able to get the output of the php code.
Is there any way to send variables from C++ to PHP and back?
Maybe using something like POST variables?
I know how to do this in flash, but I was wondering if there is a C++ equivalent.
I am learning to write C++ code to access data in a MySQL database. My goal is to use a separate class to control the database access so I can use this class elsewhere. To facilitate my learning, I'm working on simple code to connect to a database (success!) and return all rows in a simple and small table (failing!).
The connection is OK through the class constructor but I'm getting a segmentation fault in the 'queryResults = query.store()' in the class method. The backtrace, as I read it, says the failure is in a MySQL routine. (PS: The gtkmm.h is because I eventually want this class to be used by a GUI written in gtkmm.)
Any suggestions would be greatly appreciated!
Dave
[program messages and backtrace of gdb:]
Starting program: /home/dave/Code/mysql/main
[Thread debugging using libthread_db enabled]
main: Trying to instantiate db class...
database: Trying to connect to test...
database: Connection was successful.
main: After instantiation of db class
main: Calling dbselect using:SELECT * FROM SourceType ORDER BY SourceTypeId
database: Do query using SELECT * FROM SourceType ORDER BY SourceTypeId
database: Did 'query << selectsql'
Program received signal SIGSEGV, Segmentation fault.
0x00f15e94 in mysql_send_query () from /usr/lib/libmysqlclient.so.16
(gdb) bt
#0 0x00f15e94 in mysql_send_query () from /usr/lib/libmysqlclient.so.16
#1 0x00f15f30 in mysql_real_query () from /usr/lib/libmysqlclient.so.16
#2 0x00e8445f in mysqlpp::Query::store(char const*, unsigned int) ()
from /usr/lib/libmysqlpp.so.3
#3 0x00e86e05 in mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&) ()
from /usr/lib/libmysqlpp.so.3
#4 0x0804b2ae in mysqlpp::Query::store (this=0xbffff250)
at /usr/include/mysql++/query.h:467
#5 0x0804a9b7 in DataBase::dbselect (this=0xbffff238, selectsql=...)
at database.cc:31
#6 0x0804c74f in main ()
(gdb)
[end backtrace]
[my main C++ code]
#include <gtkmm.h>
#include <iostream>
#include <mysql++.h>
#include <stdlib.h>
#include "database.h"
I am writing a GUI in GKTMM for my own learning experience and to use on a personal project I have at home. The data will be stored in a MySQL database on a server I already have running in my home and which I use for some PHP/JavaScript code that supports a 'library' application I wrote to keep track of the books my wife and I read.
I have a working GUI program but need to tie it into MySQL. Should I use MySQL++ for this or one of the Gnome data access middleware systems (e.g., libgdamm)? What are the advantages of one over the other? I have doc for MySQL++ and am working on a non-GUI program to learn those classes and methods (see another post) and would appreciate if you recommend libgdamm or like middleware, if you could include a link to that doc as well.
BTW, my target system is a Ubuntu 10.04 and I may look to port it to Windows (but that's a ways down the road).
Hi, i'm new to C++ and been trying to write a simple program to compare the randomly generator number with the number input. But once i got the num1 = num2; the program keep prompting for new input. Any help would be appreciated. Thanks in advance!
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(){
char n;
int amt, num1, num2;
int count;
int tries;
srand(time(NULL));
do
{
//code for number generated from 0-99
for(int i=0; i < 1; ++i){
num2 = rand() % 100 + 1; }
cout<<num2 <<endl;
loop:
//amount input
cout << "Enter the amount $1, $2 or $5: ";
cin >> amt; // get input
//setting number of tries
switch (amt){
case 1: tries = 2;
break;
case 2: tries = 5;
break;
case 5: tries = 12;
break;
default:
cout << "Please enter $1, $2 or $5 only..." << endl; goto loop;
}
//comparing the number
do
{
for (count =0; count < tries ; ++count){
cout << "Please enter a number: ";
cin >> num1; // get input
if (num1 > num2)
cout << "Entered Number is higher than value, retry with a lower number" << endl;
else if (num1 < num2)
cout << "Entered Number is lower than value, retry with a higher number" << endl;
else if (num1 == num2)
{cout << "Congradulations, you have guess the number correctly!!" << endl; break;}
}
}while ( count < tries );
cout << "Sorry, you have exhausted all your tries..." << endl;
//To exit or continue
cout << "Enter 'N' or 'n' to exit, any other key to continue..";
cin >> n;
n = toupper(n);
}while (n != 'N');
so i am trying to write a program that reads some data in from a text file and performs an operation on that data. the text file is as follows...
611111 5
765676 4
876787 4
987897 2
611111 4
now i want the program to read that and see that 611111 is there twice and will add its corresponding values so 611111 will then have a corresponding value of 9. i did some research and found out a map is probably what i need to do this but thats where i am getting confused. im not exactly sure how to read the data into the map from a text file and then how to pick out if there are any similar numbers in the first column.
im not even sure why i am posting what i have so far since i know it is probably embarressingly wrong (especially since i have been working on this for a couple days now). thank you ahead of time!!!
in my code but he is using visual studio while am using codeblocks which just ignores the #pragma directive.is there a way to achieve that?? am using codeblocks IDE 10.05
I'm supposed to write a tcp server program which writes into a file a record as structure.
The code is given below:
int n,i;
cout<<"Enter number of student records";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter id,name,average mark";
cin>>r[i].id>>r[i].name>>r[i].mark;
}
int i,n1;
FILE *fp;
FILE *file = fopen("db.dat", "wb");
cout<<"Writing into file\n";
if ( file != NULL )
{
for(i=0;i<n;i++)
fwrite(&r[i], sizeof r[i], 1, file);
fclose(file);
}
cout<<"Writing completed\n";
There is no problem in writing part(or there is????)
When i read from the file using fread it prints junk values. What is the problem??
Does fread not place correct values in respective variables? If not how to do it??
Hi guys;
I wrote a function that inserts a new integer in the ordered link-list. If the number to insert exist in the link-list then the insertion WILL not take place, instead a message “Number To Insert Exists !!” will be produced. Can some1 help me to find out the error that makes the looping print ????
#include <iostream>
using namespace std;
typedef int value;
struct node {
value num;
node *next;
};
typedef struct node *nodePtr;
void insert(nodePtr &head, value val);
int getNumber ();
bool check (nodePtr head, value val);
void print (nodePtr head);
int main()
{
nodePtr head;
head = NULL;
value num;
//asssume only postive numbers are inserted
do {
num = getNumber();
if (num > 0)
insert(head, num);
print(head);
}while (num > 0);
system("pause");
return 0;
}
int getNumber ()
{
int num;
cout<<"Enter Number to be inserted: "<<flush;
cin>>num;
return num;
}
void insert(nodePtr &head, value val)
{
nodePtr temp;
//inserting into an empty list
if (head == NULL)
{
temp = new node;
temp->num = val;
temp->next = NULL;
head = temp;
}
else
if (!check(head, val))
{
temp = new node;
temp->num = val;
temp->next = NULL;
// find location
nodePtr findFst = head;
nodePtr findSec = head;
while (findFst->next != NULL && findFst->num < val)
{
findSec = findFst;
findFst = findFst->next;
}
if (findFst == head) //inserting in begining
{
temp->next = findFst;
findSec->next = temp;
}
else if (findSec->num < val && findFst->num >val)//inserting in the middle
{
temp->next = findFst;
findFst->next = temp;
}
else //insertion at the end
findFst->next = temp;
}
else
cout<<"Number to be inserted exists"<<endl;
}
bool check (nodePtr head, value val)
{
while (head != NULL){
if (head->num == val)
return true;
head = head->next;
}
return false;
}
void print (nodePtr head)
{
while (head != NULL)
{
cout<<head->num<<" / ";
head = head->next;
}
cout<<endl;
}
/*
* This is an example showing how to get a single file from an FTP server.
* It delays the actual destination file creation until the first write
* callback so that it won't create an empty file in case the remote file
* doesn't exist or something else fails.
*/
int main(void)
{
CURL *curl;
CURLcode res;
struct FtpFile ftpfile={
"curl.tar.gz", /* name to store the file as if succesful */
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
/*
* Get curl 7.9.2 from sunet.se's FTP site. curl 7.9.2 is most likely not
* present there by the time you read this, so you'd better replace the
* URL with one that works!
*/
curl_easy_setopt(curl, CURLOPT_URL,
"ftp://ftp.sunet.se/pub/www/utilities/curl/curl-7.9.2.tar.gz");
/* Define our callback to get called when there's data to be written */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
/* Set a pointer to our struct to pass to the callback */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
/* Switch on full protocol/debug output */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
if(CURLE_OK != res) {
/* we failed */
fprintf(stderr, "curl told us %d\n", res);
}
}
if(ftpfile.stream)
fclose(ftpfile.stream); /* close the local file */
curl_global_cleanup();
return 0;
}
#include <mysql++.h>
#include <stdlib.h>
using namespace std;
using namespace mysqlpp;
int main() {
try {
Connection conn(false);
conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
Query query = conn.query();
} catch (BadQuery er) { // handle any connection or
// query errors that may come up
cerr << "Error: " << er.what() << endl;
return -1;
} catch (const BadConversion& er) {
// Handle bad conversions
cerr << "Conversion error: " << er.what() << endl <<
"\tretrieved data size: " << er.retrieved <<
", actual size: " << er.actual_size << endl;
return -1;
} catch (const Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return -1;
}
return (EXIT_SUCCESS);
}
in curl example , how to use it? which function to declare? where to enter url?
how to get download progress and show it?
I have been playing with a piece of code that is to simulate "shortest job scheduler" for almost 2 days and there is a runtime bug which it's seems I am not able to find. Any help is really appreciated.
Here is the code:
int sjf_scheduler(int number_of_jobs, process_attrib process[])
{
process_attrib temp;
vector<int> arrival, time, pid;
cout << "\n\nNow We go to Shortest Job First Algorithm\n";
cout << "Hit a key....\n";
cin.get();
//clscr();
cout << "==================================================\n"
<< " Shortest Job First \n";
//Sort and arrange based on arrival time
for (int i = 0; i < number_of_jobs; i++)
{
for (int j = 0; j < number_of_jobs - 1 ; j++)
{
if (process[j].arrival > process[j+1].arrival)
{
temp = process[j];
process[j] = process[j+1];
process[j+1] = temp;
}
}
}
/* Now copy all the data into 3 vectors to keep the time, arrival,
* and PID */
for (int i = 0; i < number_of_jobs; i++)
{
arrival.push_back(process[i].arrival);
time.push_back(process[i].time);
pid.push_back(process[i].pid);
}
int shortest_job;
int biggest_arrival_time = process[number_of_jobs - 1].arrival;
int i, index = 0; /* Counter */
for (int tick = 0; !arrival.empty(); tick++)
{
cout << "Tick: " << tick << endl << endl;
shortest_job = 1000; /* Set the burst time to a huge value */
/* We have to get the smallest ARRIVED job */
cout << "arrival: " << arrival.size() << endl;
for (i = 0; i < arrival.size(); i++)
if (arrival[i] <= tick && shortest_job > time[i])
{
shortest_job = time[i];
index = i;
}
/* When exiting the loop, we have the shortest job by that
* specific time, now it's time to process it, as it's
* NON-Preemptive, so it takes the whole CPU time until it's
* fully finished */
cout << "Index: " << index << endl;
if (shortest_job != 1000)
{
cout << "\tProcess " << pid[index] << " finished...\n";
tick += shortest_job - 1; /* Time to finish the process */
arrival.erase(arrival.begin() + (index - 1)); /* get rid of the process */
time.erase(time.begin() + (index - 1)); /* get rid of the process */
pid.erase(pid.begin() + (index - 1)); /* get rid of the process */
}
}
cout << "********Done!!*********\n";
}
and here is the error in the console when I say "make":
/**** some parts are deleted here ****/
arrival: 2
Index: 0
Process 1 finished...
Tick: 63
I asked this before, but I have to ask again considering I still haven't found a way to do this. I need to know if there's a way to take a variable inputted into a C++ program and pass it to the terminal as an environment variable. Again, I'm running Ubuntu if it matters.
i'm having a problem on the program we're tasked to do.
originally, the "option" is an int but someone suggested to make it a character. i thought the problem was solved (i want to make the program print: "invalid output" if the user inputted non-numerical values) but when i tried to enter 11, 12, etc. it didn't go to the default part. i understand that even if you enter many characters, only one character will be read. the problem is how can allow my program to enter only one character? also, is it possible that after the user inputted a number, it function will be executed? (i mean, i don't have to enter, it will just execute automatically.)
thanks!
here's a piece of the program:
int main()
{
start_ptr = NULL;
do
{
cout << endl;
cout << "Please select an option : " << endl;
cout << "1. Add a node at the start of the list." << endl;
cout << "2. Add a node to the end of the list." << endl;
cout << "3. Delete the start node from the list." << endl;
cout << "4. Delete the end node from the list." << endl;
cout << "5. Move the current pointer on one node." << endl;
cout << "6. Move the current pointer back one node." << endl;
cout << "7. Exit the program." << endl;
cout << endl << " --->>> ";
cin >> option;
switch (option)
{
case '1' : add_start(); break;
case '2' : add(); break;
case '3' : delete_start(); break;
case '4' : delete_end(); break;
case '5' : move_current_on(); break;
case '6' : move_current_back();break;
case '7':
{ information();
system("pause>null");
exit();
break;
}
default: cout<<"INVALID INPUT!!";
}
if (option <= '7')
display();
}
while (option != '7');
}
This will probably be an easy question to answer but the solution is eluding me. I just started writing c++ programs and they work fine on my computer (I use visual studio to compile them). the problem I am having is I would run my program on another computer and I simply cant figure out how to do that without taking the source code and re-compiling it on the second computer.
Is there a way to make an .exe file or something similar that I can just put on the other computer and have it run?? Any help would be very greatly appreciated.
ANY advice would help. Even if you just say "It's im/possible"
I have a basketball league with 500 teams to schedule every year, and would love a program that would alleviate that 2-week headache. If you know of any programs that can do this, or if you are willing/able to construct a program that can do this, or if you have any advice on how I can do this myself, please let me know.
For a visual and interactive explanation, I've constructed the following so you can understand EXACTLY what I'm looking for:
I'm working on a program to save and load character files for a text-based RPG.
There are three slots to save to. I'm having the user enter whichever slot he wants to save to through inputting an integer. If the number is lower than 1 or higher than 3 I want the program to go back to the beginning, hence the do...while loop. However, it doesn't recognize overwriteSlot because it's local to the scope, and when I put it in the main loop the while section won't recognize the change in overwriteSlot, since it's happening locally. How can I make it so that it'll work. If the user enters 4, then have the whole thing restart. Thanks for any help!
int overwriteSlot;
do {
cout << "Which slot would you like to overwrite >> ";
cin >> overwriteSlot;
cin.ignore();
if (overwriteSlot <= 3) cout << "Save complete in slot " << overwriteSlot << "." << endl;
else cout << "There is no such slot!" << endl;
}
while (overwriteSlot < 1 && overwriteSlot > 3);
CompCont is a class I created that contains, for this example, one important data member, a list< pair<string,string> > connList. When I set a breakpoint at the end of each for loop, it lists comp.second.connList correctly (with only unique pairs) but as soon as it breaks out of that for loop sysRelMap goes back to having the values of each CompCont.connList to what it was before unique() and erase() were called. Hopefully this is understandable.
I'm assuming it's somehow that my functions are being passed copies of the list objects instead of references to them, but am not sure how I would modify my code to handle. I just followed many of the examples online for how to do this with the Binary Predicate function, and they all looked similar to what I have. I didn't see anything about passing references, etc, but they also weren't dealing with lists encapsulated in other objects.
My program reads water temperatures from a river as well as when the temps were recorded from an input file called "biodata.dat." Then the data is outputted in a file called "results.dat" (i havent added this results.dat part in my code but do know how to do it)
The input file looks like this:
2 // number of readings
200707211245 F70.5 // timestamp recored plus temp in Fahrenheit
200708220812 C19.97 // same but in Celsius
I am supposed to arrange the data so that the times and temperature readings(all temp readings must be in Celsius by formula) make sense, like this:
21.38C recorded on 07/21/2007 at 12:45
19.97C recorded on 08/22/2007 at 8:12.
my problem is that i dont know how to make the program only change the fahrenheit temperatures and not the celsius temperatures. how can i write something to tell them apart and use a formula to change specific temps?
btw, the formula from fahrenheit to celsius is C = 5 / 9 (F - 32)
this is the code i have so far:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
int numone;
double degrees;
string timestamp,
temp;