You can use System.IO.Directory.GetFiles(DIRECTORY_NAME);
which will return an array of strings that contain all the files (with full path) in that folder.
PulsarScript commented: Thank you +2
sfuo 111 Practically a Master Poster
Line 18 of what you posted makes no sense. It will always select maximum = maximum in the trinary operator and you cannot declare a variable equal to an undeclared variable (even if you could it would be holding a garbage value).
Line 19 you are now saying that the low guess is equal to some mystery value and your high guess is the maximum tolerated error? and then your maxError is now set to 0 and never used within your helper function.
In your helper function the only two lines that make sense are the first two where you calculate the average and the resulting fifth power of that value. Other than that I do not fully understand what you are trying to do because fifthPower - x
will not give anything useful the way you are using it (maybe if you used maxError in here somewhere then it would make sense, but then again you are setting that to 0.0).
Here is what I think you are attempting to do
#include <iostream>
#include <cmath>
using namespace std;
double fifthRootHelper(double x, double maxError, double low, double high)
{
if (x == 1.0) //special case for 1.0
return 1.0;
double avg = (low + high) / 2.0; //use 2.0 not 2 just for the future case of running into integer division without knowing
double fifthPower = avg*avg*avg*avg*avg;
if (fabs(fifthPower - x) < maxError) //if our new guess is within our error, return that as the answer
return avg;
if …
sfuo 111 Practically a Master Poster
I would suggest that you do not try to store all your information in labels, but rather have seperate variables that control the amount of each stat that your character has and then display those values in the labels.
I tossed together a quick example of how you can use buttons to increase and decrease the stats for your character. I am sure there are better ways of coding this but this should get you on track and going.
UI is here - http://i.imgur.com/zS0hM22.png
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DaniRPG
{
public partial class Form1 : Form
{
Player me;
Int32 remainingPoints;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
me = new Player();
remainingPoints = 20;
lblAgiPts.Text = me.Agility.ToString();
lblIntPts.Text = me.Intelligence.ToString();
lblStrPts.Text = me.Strength.ToString();
lblStamPts.Text = me.Stamina.ToString();
lblRemainingPts.Text = remainingPoints.ToString();
}
private void btnStrInc_Click(object sender, EventArgs e)
{
if (remainingPoints > 0)
{
me.Strength++;
remainingPoints--;
lblStrPts.Text = me.Strength.ToString();
lblRemainingPts.Text = remainingPoints.ToString();
}
}
private void btnStrDec_Click(object sender, EventArgs e)
{
if (me.Strength > 0)
{
me.Strength--;
remainingPoints++;
lblStrPts.Text = me.Strength.ToString();
lblRemainingPts.Text = remainingPoints.ToString();
}
}
private void btnAgiInc_Click(object sender, EventArgs e)
{
if (remainingPoints > 0)
{
me.Agility++;
remainingPoints--;
lblAgiPts.Text = me.Agility.ToString();
lblRemainingPts.Text = remainingPoints.ToString();
}
}
private void btnAgiDec_Click(object sender, EventArgs e)
{
if (me.Agility > 0)
{
me.Agility--;
remainingPoints++;
lblAgiPts.Text = me.Agility.ToString();
lblRemainingPts.Text = remainingPoints.ToString();
}
}
private void btnIntInc_Click(object sender, EventArgs e)
{
if …
sfuo 111 Practically a Master Poster
Not sure why you are switching values in the b array or why your swap function uses loops.
#include <iostream>
using namespace std;
int main()
{
const int N = 3;
double *a = new double[N*N];
double *b = new double[N];
double *x = new double[N];
a[0] = 9;
a[1] = 3;
a[2] = 1;
a[3] = 0;
a[4] = 4;
a[5] = 5;
a[6] = 8;
a[7] = 1;
a[8] = 4;
b[0] = 7;
b[1] = 8;
b[2] = 9;
cout << "Before" << endl;
for (int r = 0; r < N; r++)
{
for (int c = 0; c < N; c++)
cout << a[r*N + c] << " ";
cout << b[r] << endl;
}
cout << endl;
for (int r = 0; r < N; r++)
{
//"Assume" maxIndex is the first element of the row
int maxIndex = r*N;
//Check to see if the rest of the elements are greater than current max index
for (int c = 1; c < N; c++)
{
//If it is greater then set the max index to the current index
if (fabs(a[r*N + c]) > fabs(a[maxIndex]))
maxIndex = r*N + c;
}
cout << "Max = " << fabs(a[maxIndex]) << " idx = " << maxIndex - r*N << endl;
//If the max index is not a diag then lets switch it
if (maxIndex - r*N != r) //col != row aka diag
{
double tmp = a[maxIndex];
a[maxIndex] = a[r*N + r];
a[r*N + …
sfuo 111 Practically a Master Poster
Line 17 should be display->array = (char **) malloc(sizeof(char*) * height);
Note that it is sizeof(char*)
not sizeof(char)
because you are trying to allocate char pointers which have a size of 4, where a char has a size of 1.
Also your display function will not work as intended because you did not null-terminate your char arrays ('\0'). You can either null-terminate them or print the arrays out char by char, opposed to trying to print each line using the c-string format option in printf.
sfuo 111 Practically a Master Poster
Since you have just recently started learning C++ and I don't know what programming background you have. I would suggest that you learn the foundations of the language before moving on to graphics.
While you are learning the lanuage you should think of really basic "games" that you could complete in a console window (i.e. tic-tac-toe, blackjack, and other easy card games). These games will help you by making you use a many parts of the C++ language all together.
After you feel more comfortable with the language then you should really think about what IDE and graphics library you want to use. Alternativly you can use a game engine that will handle graphics, physics, sound, GUIs, and much more, but this depends on if you actually want to learn how to program or just make games that are bound by their engine. Personally I like to try to make my own "libraries" with the exception of a graphics library because that would be just crazy.
I use OpenGL and VS2012, however if you are just starting out I would suggest using SDL or another "simplified" graphics library. This way you are not spending lots of time learning the graphics library and instead you can focus on learning how to use the language and understand how a game works.
Here is the C++ tutorial website that I used to learn the language and I still use this website as a reference for the standard libraries.
Here …
sfuo 111 Practically a Master Poster
If you don't want to use the table you can just use a program to print out what the char for those hex values would be.
#include <iostream>
using namespace std;
int main()
{
char message[] = { 0x4B, 0x50, 0x7B, 0xF1, 0xF4, 0xF5, 0x5E, 0x50, 0x7B, 0xF1, 0xF4, 0xF5, 0x5E, 0x4B, 0x4B, 0x4B };
for( int i = 0; i < 16; i++ )
cout << message[i];
cout << endl;
cin.get();
return 0;
}
The message is junk but maybe you can make something out of it. I'll let you run it and see what it is.
sfuo 111 Practically a Master Poster
Or instead of using an int array you could use a map (or unordered_map if you have a compiler that supports C++11).
Accessing the values would be exactly the same but instead of having an array with a size of 97 + 26 (because 'a' is 97 (as said above) and then you need room up until 'z') you would have a map with 26 entries. Obviously maps have overhead that a normal array does not, but I think it would be good to play around with some of the STL containers so that you know how to use them and what each of them can and cannot do.
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> myMap;
for( int i = 0; i < 26; i++ )
myMap['a'+i] = i;
cout << myMap['c'] << endl;
cin.get();
}
By the way (I'm sure you just wrote it out and didn't actually test it) you defined an int array of size 10 but assigned/accessed out of bounds (in your second example).
DeanMSands3 commented: While NathanOliver and AncientDragon give "correct" answers, this is probably the most useful. +5
sfuo 111 Practically a Master Poster
When I used SDL for graphics I don't ever remember using SDL_GetKeyState(); however, it could have been just a preference that the writer turtorials I followed had.
My suggestion (it might not be the best option) is to create your own bool array to manage the key states. You can do this by calling SDL_PollEvent() and when SDL_KEYDOWN/UP is called set the key states to true/false respectivly. The major issue that I see with this is that num lock, caps lock and scroll lock all are toggled rather than having momentary states like all the other keys. So you can treat this as a special case or just ignore it if you do not plan on using those keys for anything.
The other things that I added was a fps timer since using SDL_Delay() actually freezes the program up and I changed the starting speed for the player because you cannot move with a starting value of 0.
I didn't change the whole increasing speed method but I think having to press the space bar 5 times before you notice any change is a bit odd.
"main.cpp"
#include <cstdlib>
#include <ctime> //for the timer
using namespace std;
#include <SDL.h>
#include "playertank.h"
int main ( int argc, char** argv )
{
SDL_Init(SDL_INIT_VIDEO);
unsigned int curTime = clock(); //used for fps timer rather than using delay
bool keys[SDLK_LAST]; //array of keystates
//you might want to set the initial states to that of what SDL_GetKeyState finds
//since for some reason it could find …
sfuo 111 Practically a Master Poster
Actually the code post is exactly what you wanted for the whole conversion from one base to another. This is just set to hex, if you want to it be general then replace all the 16s with a variable and expand the alphabet to Z.
You can write a check minimum base function and pass A, B and Z/R into it then run a loop checking to see if A + B = Z and A x B = R with the current base, if not then check the next. If you hit the maximum allowable base then return 0. If you find a base that works then run it to the end to see if it is unique or not.
If you cannot figure this out now then you are hopeless!
sfuo 111 Practically a Master Poster
By the way 120 can be of any base from 3 to inf.
Thats exactly what hes getting at. If you want to convert A2C3 you have to say what base it is in because this could be anything from base 13 to infinity the way you see it.
If you are assuming that A2C3 is in hex then you can loop through the string, converting each hex char to decimal and then add it to an integer variable.
#include <iostream>
#include <cmath>
using namespace std;
int hex2dec(string hexstr)
{
int decval = 0;
for( unsigned int i = 0; i < hexstr.size(); i++ )
if( hexstr[i] >= '1' && hexstr[i] <= '9' )
decval += (hexstr[i] - '0')*pow(16, hexstr.size()-1-i);
else if( toupper(hexstr[i]) >= 'A' && toupper(hexstr[i]) <= 'F' )
decval += (toupper(hexstr[i]) - 'A' + 10)*pow(16, hexstr.size()-1-i);
return decval;
}
int main()
{
int num = 0xA2C3;
cout << num << endl;
cout << hex2dec("A2C3") << endl;
cin.get();
return 0;
}
sfuo 111 Practically a Master Poster
From reading the wiki page for Greatest common divisor (GCF) it show to use Euclid's algorithm to find the GCF. The link that shows some pseudocode for using the algorithm is here.
And here is a recursive implementation.
int GCF(int a, int b)
{
return ( (b == 0) ? a : GCF(b, a%b) );
}
sfuo 111 Practically a Master Poster
Yeah if you wanted to have it work for 2D and 3D points then you could either overload the function to do both 2D and 3D "hardcoded" or you can use a loop to sum all the squares then take a single squareroot at the end.
Example
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
double Distance(vector<double> pt1, vector<double> pt2)
{
if( pt1.size() != pt2.size() )
return 0;
double sum = 0;
for( unsigned int i = 0; i < pt1.size(); i++ )
sum += (pt2[i]-pt1[i])*(pt2[i]-pt1[i]);
return sqrt(sum);
}
int main(int argc, char *argv[])
{
vector<double> pt1, pt2;
pt1.push_back(150);
pt1.push_back(50);
pt2.push_back(15);
pt2.push_back(20);
cout << Distance(pt1, pt2) << endl;
}
sfuo 111 Practically a Master Poster
I kind of see what you are trying to do with the nested for() loops but it is wrong.
For distance I would just make a function that takes in the two coordinates, or this 4 element array, and then just plug it into the formula.
Also in C++ you want to use the cmath library for math and not the math.h C version.
#include <iostream>
#include <cmath>
using namespace std;
double Distance(int x1, int y1, int x2, int y2)
{
return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
double Distance( int coords[4] )
{
return sqrt((coords[2]-coords[0])*(coords[2]-coords[0]) + (coords[3]-coords[1])*(coords[3]-coords[1]));
}
int main(int argc, char *argv[]) {
int coord[2*2] = {150, 50,
15, 20};
cout << Distance(coord[0], coord[1], coord[2], coord[3]) << endl;
cout << Distance(coord) << endl;
}
phorce commented: Thank you! :)!!! +4
sfuo 111 Practically a Master Poster
The code that you are using for checking who wins is pretty bulky. If you just treat the hands like 0, 1 and 2 and that higher numbers beat lower numbers with the exception that 0 beats 2 then you can just use the mod operator to wrap around and see who wins.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
int player, cpu;
char option;
int wins = 0, losses = 0, ties = 0;
char hands[3] = {'r', 'p', 's'};
while(1)
{
cout << "Enter (R)ock, (P)aper, (S)cissors, or (Q)uit:" << endl;
cin >> option;
if( tolower(option) == 'r' )
player = 0;
else if( tolower(option) == 'p' )
player = 1;
else if( tolower(option) == 's' )
player = 2;
else if( tolower(option) == 'q' )
break;
else
continue;
cpu = rand()%3;
cout << "Player | CPU" << endl;
cout << hands[player] << " " << hands[cpu] << endl << endl;
if( player == cpu )
{
cout << "Tie!" << endl;
ties++;
}
else if( player == (cpu+1)%3 )
{
cout << "Player wins!" << endl;
wins++;
}
else
{
cout << "CPU wins!" << endl;
losses++;
}
cout << "Score:" << endl;
cout << "w: " << wins << " | l: " << losses << " | t: " << ties << endl << endl;
}
return 0;
}
I added in a score keeping feature too.
sfuo 111 Practically a Master Poster
Yeah sorry my wording may have been a bit misleading. The variable i does have a value of 4; however, acc[i] contains a junk value. So what I guess I should have said is that your array "acc" has a junk value at index i and anything past that (since it is not being set anywhere).
Now what I do not know is why it is crashing for trying to access the index of the array with that junk value. I tried accessing the array at a large index and it just spat out a junk number but when I typed in a value of ~100000 or so it crashed like before. I'm not sure if there is a "magic" number around there but I'm sure there is a hard limit or just undefined behaviour going on. Either way you don't every play out of bounds like that anyways because you could be overwriting other allocated blocks of memory or could just simply crash like this.
sfuo 111 Practically a Master Poster
Your second for() loop is causing the crash because the first for() loop leaves i at a an index with a junk value since it increments then checks to see if ip_num is 0.
There are two quick ways to fix this:
1) You can assume that ip_num is never zero when entering the loop on the first run and move the break condition to the bottom of the loop.
2) You can start the second for() loop with i = i-1 (or i--).
Either way works and I'm sure there are many other ways to go about solving this problem but I didn't want to modifiy what you had too much.
sfuo 111 Practically a Master Poster
As far as functionality goes it works; however, you shouldn't be using labels/gotos because they are a bad coding habbit and make reading the flow of your code harder. Anywhere you use a goto statement you can replace it with a loop (which is what I did in this case).
Another thing that you should think about is making variable names that actually mean something. When I saw p, f, d, b I had no idea what those were until I looked over the program. So instead of using p as a name for your array of workers you can just call it workers or something descriptive.
You should also know that most programming languages are 0 base indexed so if you want an array that has 10 entries, it starts at 0 and ends at 9.
If you wanted to make this a bit more C++ rather than C you could use strings for the name of the worker and job, also you could use a vector, list or any other STL container that can dynamically resize to however many workers you want to create (or read in from the file if you want to add that feature).
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
struct work
{
char name[100];
int id;
char job[10];
}workers[10];
int main()
{
int numWorkers = 0;
int option = 0;
ofstream file;
while(1)
{
cout << "\nThe db++ Database application\n1-To enter the data\n2-To read the data\n3-To save the data\n";
cin >> …
piyush3dxyz commented: hey sfuo....i am the beginner in the c++ programming...Its only 2 month of my c++ learning.....but thax for correcting me.... +0
sfuo 111 Practically a Master Poster
I have attached a rewrite of your program because if you ever want future help your code has to be structured.
I would recommend having main.cpp with pretty much just main() in it so you can read the flow of the program and if you want to know what happens in a function then you go open up that header/source file.
Obviously this is just the way I like to structure small games like this and others would disagree/change aspects of it; however, I would hope everyone would agree that having 99% of your code in main.cpp just makes finding errors extremely difficult.
There were many areas where you used the comparison operator (==) rather than the assignment operator (=) which doesn't do what you want and if you have warnings turned off it doesn't tell you that it does nothing.
As far as fixing the problem with the box goes, I changed it so that the dropping of the box is handled by the player class rather than having a seperate handle for the box. The main issue with the box in the first place was that you were making it visible by setting drop to true then right after you released the key you set it to false (which makes the box disappear).
If you have any questions feel free to ask.
This attachment is potentially unsafe to open. It may be an executable that is capable of making changes to your file system, or it may require specific software to open. Use caution and only open this attachment if you are comfortable working with zip files.
ChrisMackle commented: THANK YOU!!!! +0
sfuo 111 Practically a Master Poster
On line 11 your function prototype says that approximateSqrt() takes no parameters so that is where that error is coming from. To fix it change that line to double approximateSqrt(double);
sfuo 111 Practically a Master Poster
You don't have a display function or an idle function. Not 100% sure if this is the problem since I haven't used glut in a while but from what I remember you need them.
sfuo 111 Practically a Master Poster
Like VernonDozier said, you are declaring 'char c' out of scope but there are also a few other errors within your program.
You are calling the function srand() at the start of the for() loop on each iteration which results in all the characters being the same. The solution to this is to call srand() once either at the start of this function or at the beginning of main() (I would suggest placing it at the start of main()).
The second problem is the range for your rand() function. You had rand() % 26;
which will generate a number from 0 to 25 not 0 to 26. So the solution is to just set your maximum to the maximum value in your range + 1.
I did a bit of tweaking and shortened your append section but for the most part it is the same.
Also notice that srand() is not being called here because it should be at the start of main().
string genstring()
{
string generated_string;
string stringsize = inputsentance();
for( unsigned int k = 0; k < stringsize.size(); k++ )
{
char c = rand() % 27 + 'A'; //random from "A-["
if( c == '[' )
c = ' ';
generated_string.append(1, c);
}
return generated_string;
}
sfuo 111 Practically a Master Poster
Without actually knowing how it is implemented and by only playing around with these two classes it seems when there is a name conflict (in this case x) the default scope to be used is that of the class that is calling it. When inheriting another class the class that is being inherited is added to the scope of the "inheriter" if there is no conflict.
For example
class B
{
public:
int x;
};
class D: public B
{
public:
int x;
};
would result in 'D' looking like
class D: public B
{
public:
int D::x; //in the default scope so 'D d.x' would look at this
int B::x; //name conflict so would need to use 'D d.B::x' to access
};
As for implementing a structure like this in C I would say it is impossible to put two variables with the same name into the same structure since there are no namespaces or 'built-in' inheritance in C. I came across this page and it goes over how to make classes with functions and inheritance in C (I didn't read it that much just scrolled through it).
sfuo 111 Practically a Master Poster
The issue lies within your function gasket().
On line 34 you are missing an equals sign between point and T, so it should look like
GLPoint point = T[index];
Then when you are adding point.x and t[index] then dividing by 2 you really want to add each component then divide by two. So line 42 and 43 should look like
point.x = (point.x + T[index].x) / 2;
point.y = (point.y + T[index].y) / 2;
Also I'm not sure about you but when I try to compile it gives me a bunch of undefined reference errors about all the OpenGL functions, so at the top I had to put
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
sfuo 111 Practically a Master Poster
It looks like all your errors/problems are in "cdrom.cpp".
In the function CDROM::setName() you have getline(cin, name)
being printed out in your cout statement. The function getline() returns *this which is a pointer to the istream object being used (I think, either way this is not what you want). Also you have cin.ignore() being used which is pointless because getline() reads the '\n'. cin.ignore() should be used after reading in a number (int, float, double) because when reading in a number you only read in digits, decimals and signs (+/-), which results in characters typed in after to be left in the input buffer (ie "22char\n" results in "char\n" being left in the input buffer).
The next function, CDROM::setType(), has the exact same problem as CDROM::setName() so get rid of the cin.ignore() and do not output getline().
In CDROM::setCost() you want to clear the input buffer after you input the number because it leaves characters in the buffer, but you do this after you get the input not before. In order to use the line cin.ignore(numeric_limits<streamsize>::max(), '\n');
you need to include <limits> at the top because numeric_limits<streamsize>::max() is defined within it. If you do not clear the input buffer then when this loops for the next CDROM input you will not see text pop up until you type in something.
Here is what I did to correct the errors.
void CDROM::setName()
{
cout << "Please enter name : ";
getline(cin, name);
}
void CDROM::setType()
// …
sfuo 111 Practically a Master Poster
Since it says there are no duplicate inputs I'm guessing (and there is no way to check) there will be no need for checking if a duplicate number was entered. You can throw on a check to restrain input from [0,n).
This is what I came up with "1 day ago" according to this thread.
#include <iostream>
using namespace std;
int main()
{
int n = 10, inpt;
for( int i = 0; i < n; i++ )
cin >> inpt;
for( int i = 0; i < n; i++ )
cout << i << endl;
return 0;
}
sfuo 111 Practically a Master Poster
I wrote this linked list a while ago. After reading yours for a bit I went back and modified mine to use templates and used your names.
You can take a look at this and use what you want.
It has four functions:
Add() which appends a node to the list
AddAt() which inserts a node at an index
AddAfter() which inserts a node after the named node
Print() displays the contents of the list
#include <iostream>
using namespace std;
template <typename T>
struct Node
{
Node(){};
Node( T n )
{
name = n;
next = NULL;
}
T name;
Node *next;
};
template <typename T>
class List
{
Node<T> *first;
public:
List()
{
first = NULL;
}
void Add(T name) //adds a new entry to the list
{
Node<T> *newNode = new Node<T>(name);
Node<T> *curNode = first;
if( curNode == NULL )
{
first = newNode;
return;
}
while(curNode->next != NULL)
{
curNode = curNode->next;
}
curNode->next = newNode;
}
void AddAt(T name, int index)
{
Node<T> *newNode = new Node<T>(name);
Node<T> *curNode = first;
Node<T> *nexNode = 0;
Node<T> *prvNode = 0;
if( curNode == NULL )
{
first = newNode;
return;
}
int i = 1;
while(curNode->next != NULL && i != index)
{
prvNode = curNode;
curNode = curNode->next;
i++;
}
if( i != index )
{
curNode->next = newNode;
return;
}
if( prvNode == NULL )
{
nexNode = first;
first = newNode;
newNode->next = nexNode;
return; …
Braindead90 commented: Gave a detailed explanation of suggestion even with comments inside code... Very Helpful +0
sfuo 111 Practically a Master Poster
I would use two for() loops. You can use a while() loop but I tend to avoid them when you want to count through a range of values.
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "Enter a positive integer: " << endl;
cin >> num1;
cout << "Enter another positive integer: " << endl;
cin >> num2;
if( num1 > num2 )
{
int tmp = num1;
num1 = num2;
num2 = tmp;
}
//low to high
for( int i = num1; i <= num2; i++ )
cout << i << " ";
cout << endl;
//high to low
for( int i = num2; i >= num1; i-- )
cout << i << " ";
cout << endl;
return 0;
}
I didn't throw in any checking for the two inputs.
sfuo 111 Practically a Master Poster
One huge problem that you had was that you were not allocating memory for your stack. The reason why you did not get run-time errors for this is because you were never actually using your stack, which is why (along with a few other things) you were getting garbage values for the initial test.
Within the oper() function you have a check that attempts to see if there are at least two numbers in the stack and in your case that is never true so it just returns. I would suggest you remove that all together and take advantage of the fact that your pop() functions return a bool.
Out of all the functions you have the only one that is correct is the pop() function. Your push() function is changing the memory address of mPtop when what you really want is to change the value at mPtop's memory address, and you need a range restriction on that function so you are not pushing too many values onto a stack of a limited size (otherwise you go out of bounds of the memory allocated and this results in a run-time error).
For the oper() function your division function is wrong and you need to look up how to divide complex numbers (I just typed in dividing complex numbers into google) and attempt to come up with the same result that I put below (I did it all with variables on pen and paper and then transferred it …
sfuo 111 Practically a Master Poster
This sounds like a trick question to me because if n was 50 or something and I gave the input 20, 30, 21, 49, 1, 35, ... 0 how would you be able to sort that without having a variable for each input.
To "sort" a bunch of input in ascending order with n numbers and no duplicates can be done by using a for() loop
for( int i = 0; i < n; i++ )
cout << i << endl;
sfuo 111 Practically a Master Poster
One big thing you have to understand is that a function (ie main()) is not a class.
Classes hold variables and functions which can be accessed/used via the "dot" (.) operator.
Here is an example of an Event_Time class that prints out the current date and time when you call the function CurrentTime().
#include <iostream>
#include <ctime>
using namespace std;
class Event_Time
{
time_t current_seconds;
tm *timeinfo;
char buffer[80];
public:
void CurrentTime()
{
current_seconds = time(NULL);
timeinfo = localtime(¤t_seconds);
strftime( buffer, 80, "Event Date: %x", timeinfo );
cout << buffer << endl;
strftime( buffer, 80, "Event Time: %X %Z", timeinfo );
cout << buffer << endl;
}
};
int main()
{
Event_Time event; //creates a new event
event.CurrentTime(); //displays the current time
return 0;
}
Notice how there is no assignment done outside of functions within the class (if you want to declare and initialize at the same time outside of functions within the class then it must be a static constant variable (ie static const int x = 5
).
If you want to initialize variables right when the object is made then you either call a function that assigns or you define a constructor for the class.
Here is an example using a constructor.
#include <iostream>
using namespace std;
class myClass
{
int myVariable;
public:
myClass() //Constructor. Notice that it does not have a return type. This will replace the default constructor.
{
myVariable = 5;
}
myClass( int in ) //This …
sfuo 111 Practically a Master Poster
I think your method in general is the problem. I looked up Knight's Tour in Wikipedia and read the Wansdorff section and came up with my own code. This method is really easy to implement because I had never heard of this Knights Tour puzzle and I put this together in a few hours.
The only thing that might be slightly advanced and you have not seen is a structure and its operators but the whole point they were put in was because it is easier to think in objects (a position has an x and y value and then the operators just allow you to add them together).
Here is what I came up with and it is loosely based off yours.
#include <iostream>
#include <ctime>
#include <cstdlib> //used for CLS and PAUSE
#include <cstring>
using namespace std;
//board size
#define XDIM 8
#define YDIM 8
struct position
{
int _x, _y; //data
position(int x = 0, int y = 0) //constructor (default values of 0, 0)
{
_x = x;
_y = y;
}
position operator +(position rhs) //allows the use of the + operator with position structures
{
return position(_x+rhs._x, _y+rhs._y);
}
void operator += (position rhs) //allows the use of the += operator with position structures
{
_x += rhs._x;
_y += rhs._y;
}
};
bool Move(bool[][YDIM], position&);
void PrintBoard(bool[][YDIM], position);
int GetNextMove(bool[][YDIM], position);
int GetNumMoves(bool[][YDIM], position, bool = false);
int GetFewestMoves(int[8]);
position moves[] = {position(-2, 1), position(-1, 2), position(1, 2), …
sfuo 111 Practically a Master Poster
He is lucky that this works. The reason it does is because when you declare an array the last element is automatically set to NULL (which is 0). Then you use getline() which extracts n-1 characters and adds a NULL at index n. So now you have two NULL characters in a row. Then you come to the while loop that checks element 50 (which is NULL) and that is less than 100 and then you increment the 50'th element by one each time. If you did not use getline() then you would have junk being printed out after the name you entered if the name was as long as the array was. This is because you are overwriting the original NULL character that the array created when the array is being made.
The "proper" (because there are many ways to do this) way of doing this is to use a for() loop that uses an integer to count to 100.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char name[50];
cout << "Insert Name" << '\n';
cin.getline(name, 50);
for( int i = 0; i < 100; i++ )
{
cout << name << '\n';
}
return 0;
}
I would really not recommend doing what you did because you might not be running into problems with it now, but something will happen if you do not use getline() or if you use getline() with an extraction size of your arraysize + 1.
sfuo 111 Practically a Master Poster
I can't really tell what you are trying to do since the code on google docs is really old (still has errors from last post).
Is this along the lines of what you are trying to accomplish?
struct SDL_Rect //I made this because I didn't want to include all the SDL stuff
{
int x, y, w, h;
};
class Platform
{
int numClips;
SDL_Rect *clips;
public:
Platform()
{
numClips = 50; //so you can know how many clips you have externally rather than hardcoding all throughout your game
clips = new SDL_Rect[numClips]; //create 50 clips
}
SDL_Rect *getClips()
{
return clips; //returns pointer to the first clip
}
int getNumClips()
{
return numClips;
}
~Platform()
{
delete clips;
clips = 0;
}
};
bool check_collision(Platform B)
{
int leftB;
for( int i = 0; i < B.getNumClips(); i++ )
{
leftB = B.getClips()[i].x;
}
return true;
}
int main()
{
Platform A;
check_collision(A);
return 0;
}
sfuo 111 Practically a Master Poster
If you want us to try to compile your code then you should post it in code tags in here because most of the formatting is lost when I try to copy paste it from the rtf file.
The big thing that I see, and I'm not sure if its the only problem since I have no images and I don't really wanna re-tab all your code each time you post, is that you have SDL_Rect levelOnePlatform[1];
when you should have it with a size of 50 since that is what you are passing into it when you try clipping it.
sfuo 111 Practically a Master Poster
The problem is in the constructor. You are declaring three new integers (x, y and frame). After the constructor is done those three do not exist and stick::x, stick::y, stick::frame are not modified at all. So what you need to do is remove int from in front of
x = 0;
y = 0;
frame = 0;
so that it modifies the stick's variables.
If you cant get your debugger working then just enable the console window and use cout. Or if you are using visual studio and for whatever reason the console window doesn't wanna show up, you can use fstream and write to a file. Because I ran your code with outputs and saw that x and y were huge values which normally means that they are uninitialized.
sfuo 111 Practically a Master Poster
Here is a method using recursion that you could use.
If you would want this to work with rocket mania then you would need to do checking to see if the two pipes line up rather than just replacing the character like the function does below.
#include <iostream>
#include <cstdlib> //remove this if you are not using windows/dont want time delay redraw
#include <cstring>
#include <ctime> //remove this if you are not using windows/dont want time delay redraw
using namespace std;
void Print(char[][5]);
size_t resetTime = clock(); //remove this if you are not using windows/dont want time delay redraw
void Search(int x, int y, char board[][5])
{
if(board[x][y] != 'o')
return;
board[x][y] = '*';
Print(board); //remove this if you are not using windows/dont want time delay redraw
if( x > 0 )
Search(x-1, y, board);
if( y > 0 )
Search(x, y-1, board);
if( x < 4 )
Search(x+1, y, board);
if( y < 4 )
Search(x, y+1, board);
}
void Print(char board[][5])
{
while( clock() - resetTime < 500 ){}; //remove this if you are not using windows/dont want time delay redraw
resetTime = clock(); //remove this if you are not using windows/dont want time delay redraw
system("CLS"); //remove this if you are not using windows/dont want time delay redraw
for( int i = 0; i < 5; i++ )
{
for( int c = 0; c < 5; c++ )
cout << board[c][i] << " ";
cout << endl;
}
cout << endl << endl;
}
int …
daniel955 commented: appreciated the help. +2
sfuo 111 Practically a Master Poster
Would look more like a circle if the characters were square and line spacing was the same as character spacing.
#include <iostream>
using namespace std;
int main()
{
double r = 1.2;
for( double y = -r-0.1; y <= r+0.2; y += 0.1 )
{
for( double x = -r-0.1; x <= r+0.2; x += 0.1 )
{
if( (x*x + y*y <= (r*r)*1.1) && (x*x + y*y >= (r*r)*0.9) )
cout << "*";
else
cout << "#";
}
cout << endl;
}
return 0;
}
Output:
###########################
##########*******##########
#######****#####****#######
######**###########**######
#####**#############**#####
####*#################*####
###**#################**###
##**###################**##
##*#####################*##
##*#####################*##
#**#####################**#
#*#######################*#
#*#######################*#
#*#######################*#
#*#######################*#
#*#######################*#
#**#####################**#
##*#####################*##
##*#####################*##
##**###################**##
###**#################**###
####*#################*####
#####**#############**#####
######**###########**######
#######****#####****#######
##########*******##########
###########################
sfuo 111 Practically a Master Poster
5050 is the sum of the numbers from 1-100.
You are printing the value returned from counter in main() so it will only print once.
If you want to print all the numbers from 1-100 you should have your print statement within the recursive function and you do not need to have the function return anything (make it a void function).
chaoz014 commented: thank you... +0
sfuo 111 Practically a Master Poster
If its C++ then you should post in the C++ forum.
You should also post the code that you have so far.
What you need is a float that holds the total of all the items being entered. A float to hold the amount of money the user gives. Then output the amount of money the person gave minus the total of all the items and that will give you the change.
Salem commented: Nice +17
sfuo 111 Practically a Master Poster
I actually started with C++ so I learned from http://www.cplusplus.com/doc/tutorial/ but learning loops, variables and arrays is common between the two of them.
sfuo 111 Practically a Master Poster
If you wanna store the names like a = ant
you should use strings (char*).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define sz 12
int main()
{
int i, j;
char* animals[sz] = {"ant", "bear", "cat", "dog", "emu", "goat", "lizard", "monkey", "parrot", "rabbit", "snake", "tiger"};
char* chosen[4] = {"", "", "", ""};
srand(time(NULL));
for( i = 0; i < 4; i++ )
{
chosen[i] = animals[rand()%12];
for( j = 0; j < 4; j++ )
if( strcmp(chosen[i], chosen[j]) == 0 && j != i ) //checks to see if the animal picked is unique
{
i--; //if not decrease counter so it overwrites the last animal
break;
}
}
for( i = 0; i < 4; i++ )
{
printf("%c - ", chosen[i][0]); //for first letter of animals name
printf("%s ", chosen[i]); //for whole name of animal
}
printf("\n");
return 0;
}
ineedsomehelp:3 commented: Very informative :) +0
sfuo 111 Practically a Master Poster
After fixing a bunch of typos and added to the bottom of Advanced2D.cpp (you have the extern prototypes but you do not actually make the functions)
bool game_init(HWND in)
{
return true;
}
void game_update()
{
}
void game_end()
{
}
bool game_preload()
{
return true;
}
Make sure you include the libraries
d3dx9.lib
d3d9.lib
winmm.lib
And you really need to work on formatting the code since it was really difficult to figure out where the problems were.
Sudo Bash commented: good for you, reading all that code. +1
sfuo 111 Practically a Master Poster
You could use a map to help decode the message.
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, char> cipher;
cipher["45"] = 'd';
cipher["32"] = 'o';
cipher["34"] = 'v';
cipher["56"] = 'e';
string encoded = "45323456", decoded = "";
for( unsigned int i = 0; i < encoded.length(); i+=2 )
decoded += cipher[encoded.substr(i, 2)];
cout << decoded << endl;
return 0;
}
sfuo 111 Practically a Master Poster
You make a new thread, show your code and tell us some of the problems you have.
sfuo 111 Practically a Master Poster
You could use two functions for drawing like this.
void RenderOverlay( GLenum mode )
{
glViewport(0, 0, (GLsizei) WINDOW_WIDTH, (GLsizei) WINDOW_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glTranslatef(0,0,0); //dont actually have to do since it is default 0
//also have rotation at 0
ORTHO_WIDTH = ORTHO_HEIGHT*((GLdouble)WINDOW_WIDTH/(GLdouble)WINDOW_HEIGHT);
glOrtho(0, ORTHO_WIDTH, 0, ORTHO_HEIGHT, -1, 20);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//draw your crosshair and other HUD elements
glPushMatrix();
glBegin(GL_QUADS);
glEnd();
glPopMatrix();
glPopMatrix();
}
void RenderScene( GLenum mode )
{
glViewport(0, 0, (GLsizei) WINDOW_WIDTH, (GLsizei) WINDOW_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
camera.Position();
gluPerspective(60, (GLfloat) WINDOW_WIDTH/ (GLfloat) WINDOW_HEIGHT, 0.1, 60.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//draw world objects
glPushMatrix();
glBegin(GL_QUADS);
glEnd();
glPopMatrix();
glPopMatrix();
}
I doubt you can use this code directly but hopefully you can get an idea of the method I'm showing.
pcgamer2008 commented: Showed me a light...thanks !! +1
sfuo 111 Practically a Master Poster
There are quite a few problems with this code.
#1) The run-time error is caused because you are trying to remove the first two digits of your decimal input and it is crashing because you use the itoa() function which takes an integer and converts it into a cstring. You are using a double which if it is less than 0 it will be put in as 0 (because an integer is a whole number and does not hold any decimal places). Then you try to substring that and say start at 2 and copy the next 2 elements. Since your string is only holding "0" you are trying to cut it out of bounds therefore making it crash.
#2) Another problem that you would run into later would be the fact that you are allowing an input of "0.01". This resistor would be Brown, Black, "??" (something that is 10^-3), Tolerance which doesn't exist on the 4 band resistors. Meaning you have to limit it to "0.1" because that would be Brown, Black, Silver, Tolerance.
To solve problem #1 I would completely scrap the function itoa() since it is old and uses cstrings when you are just converting them into strings afterward anyways. Use the stringstream object (you already have the header added and use it elsewhere) to insert your resistance after doing bounds checking then find the two significant digits and where the decimal place is to determine the multiplier.
I have …
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
class RESISTOR
{
double resistance;
int tolerance;
static vector<string> bands; //static so you can assign it without copying/assigning in a constructor
static string colors[]; //same as above
public:
bool SetResistance(); //gets user input and sets the first 3 bands
bool SetTolerance(); //gets user input and sets the 4th band
void DisplayBands(); //displays the 4 bands
};
vector<string>RESISTOR::bands(4, "Black"); //creates 4 "bands" that are default Black (incase user types in "1" for resistance then 2nd band will be black by default)
//instead of constantly typing out all the colors create an array and use basic math to set colors of the bands
string RESISTOR::colors[] = {"Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Gray", "White", "Gold", "Silver", "None"};
int main()
{
RESISTOR ohm; //call it whatever
if(ohm.SetResistance()) //if goes wrong in setting the value it just quits
if(ohm.SetTolerance()) //if goes wrong in setting the value it just quits
ohm.DisplayBands(); //display the 4 bands
return 0;
}
bool RESISTOR::SetResistance()
{
double resistNum;
string resistStr;
int multiplier, decimalLoc, secondSigDigitLoc;
char answer;
do
{
cout << "\nPlease enter the desired resistance \nvalue in ohms (0.1 ohms to 100,000,000 ohms): ";
cin >> resistNum;
answer = 'n';
if( resistNum < 0.1 || resistNum >= 100000000 ) //use OR not AND otherwise it will never be true
{
cout << "Invalid Input! Would you like to try again? Enter Y: " ;
cin >> answer;
if( answer != 'Y' && answer != 'y' )
return false;
}
} while(answer == 'y' || answer == 'Y');
stringstream strm;
strm << fixed << resistNum; //use fixed otherwise it will convert large numbers to scientific notation
strm >> resistStr;
cout << resistStr << endl;
//finds the first two significant numbers (band 1 and 2)
for( unsigned int i = 0, c = 0; i < resistStr.length() && c < 2; i++ )
if( !(c == 0 && resistStr[i] == '0') && resistStr[i] != '.' )
{
bands[c] = colors[resistStr[i]-'0']; //converts digit (that is a char) to an int
c++;
}
//finds the position of the decimal
secondSigDigitLoc = -1;
for( unsigned int i = 0; i < resistStr.length(); i++ )
{
if( resistStr[i] == '.' ) //there will always be a decimal because the number was inserted with "fixed"
decimalLoc = i-1;
else if( resistStr[i] != '0' && secondSigDigitLoc == -1 )
secondSigDigitLoc = i+1;
if( i == resistStr.length()-1 && secondSigDigitLoc == -1 )
secondSigDigitLoc = 0;
}
//calculate and assign a color to the 3rd band
multiplier = decimalLoc-secondSigDigitLoc;
if( multiplier < 0 )
bands[2] = colors[(multiplier*-1)+9]; //if it is negative then multiply the number by -1 and add 9 to it to get the color index
else
bands[2] = colors[multiplier];
return true;
}
bool RESISTOR::SetTolerance()
{
int tolerance;
char answer;
do
{
cout << "\nPlease enter the desired tolerance as a percentage(5, 10, or 20): ";
cin >> tolerance;
answer = 'n';
if (tolerance != 5 && tolerance != 10 && tolerance != 20)
{
cout << "Invalid Input! Would you like to try again? Enter Y: " ;
cin >> answer;
if( answer != 'Y' && answer != 'y' )
return false;
}
} while(answer == 'y' || answer == 'Y');
bands[3] = colors[(tolerance/10)+10]; //this only works for 5, 10, 20 because 5/10 = 0, 10/10 = 1, 20/10 = 2, add 10 and that gives you the index of the color
return true;
}
void RESISTOR::DisplayBands()
{
for( unsigned int i = 0; i < bands.size(); i++ )
cout << i+1 << ": " << bands[i] << endl;
}
jonsca commented: Nice job +14
sfuo 111 Practically a Master Poster
For the first two errors make sure that you either have both of the classes above Point2D class or just put the class prototypes above the Point2D class
class aRectangle;
class Offset;
As for the 3rd and 4th errors (4th is caused by the 3rd) you probably do not have a Offset variable declared within main().
The previous question is a messy mixture of OO and non-OO code. Tidy up the cody by:
1) implement class Offset and use an offset object as an argument to the member function MoveRelative(). An offset object has two values that are added to the x and y vlaue of a point.
2) Implement class aRectangle and use an aRectangle object as an arguement to the contains method
To me this does not sound like he wants you to use friendship/inheritance.
sfuo 111 Practically a Master Poster
I don't think you have to use any inheritance for the aRectangle class like your last post says.
And the way I set this up I'm not too sure why he got you to use classes for Offset and aRectangle, unless he wants you use get() and set() functions to assign values, when you could just use structures since they start off being public (opposed to classes which start out private).
Point2D.h changes/additions
class Offset
{
public:
Offset(int x = 0, int y = 0)
{
_x = x;
_y = y;
}
int _x, _y;
};
class aRectangle
{
public:
aRectangle(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0)
{
_x1 = x1;
_y1 = y1;
_x2 = x2;
_y2 = y2;
}
int _x1, _y1, _x2, _y2;
};
//changes within the Point2D class
void moveRelative(Offset oset)
{
x += oset._x;
y += oset._y;
}
int contains(aRectangle rect)
{
if (x <= rect._x1 && x >= rect._x2)
{
if (y <= rect._y1 && y >= rect._y2)
return 1;
else
return 2;
}
else if (y <= rect._y1 && y >= rect._y2)
{
if (x <= rect._x1 && x >= rect._x2)
return 1;
else
return 3;
}
return 0;
}
main.cpp changes/additions
int main(int argc, char* argv[]) //might look different because I use code::blocks and it doesn't like your format (just change it back)
{
Point2D aPoint; //unchanged
aRectangle rect(8,6,4,2); //declare a rectangle
Offset oset; //declare an offset
int …
ghost_from_sa commented: works :) +1