• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Onemic

Member
I'm guessing it's the one = sign in your denominator = 0 statement. The logic seems sound. And it worked perfectly fine in my Python conversion of the code.

yup, forgot to put two = signs instead of one. I hate hard to find bugs like that, so much time wasted over such a small error.
 

Water

Member
yup, forgot to put two = signs instead of one. I hate hard to find bugs like that, so much time wasted over such a small error.
You probably didn't only write a bug, but also failed to turn on warnings in the compiler. Most good compilers will notice and warn you for having an assignment inside a condition to prevent exactly this thing.
 

Onemic

Member
You probably didn't only write a bug, but also failed to turn on warnings in the compiler. Most good compilers will notice and warn you for having an assignment inside a condition to prevent exactly this thing.

There was a warning at that line, but the description provided was some jibberish about not having parenthesis around an assignment. Didn't really know what that meant. Guess I do now, heh
 

Slavik81

Member
There was a warning at that line, but the description provided was some jibberish about not having parenthesis around an assignment. Didn't really know what that meant. Guess I do now, heh

Look closer and it probably describes exactly what's wrong. If you really want to do an assignment in a conditional, you can add parentheses to suppress the warning in gcc. The warning likely explains that.

That fact was exploited in someone's (failed) attempt to put a backdoor into Linux back in 2003.
 
nevermind. i hate myself.

my void draw(graphics g) was wrong

Code:
		// g.drawRect((int) getX(), (int) getY(), width, height); // x loc, y loc, width, height

should be
Code:
			g.drawRect((int) getLocation().getX(), (int) getLocation().getY(), width, height);
 

Dr_Swales

Member
nevermind. i hate myself.

should be
Code:
			g.drawRect((int) getLocation().getX(), (int) getLocation().getY(), width, height);

Glad you found your solution :)

As a side note, the type casts you have use
Code:
(int) getLocation().getX()
are C-style casts. Where in C++ you would generally use a functional cast
Code:
int(get location().getX())
it's not a problem, but it will help when you come to learn C++ casts on pointers.
 

Water

Member
As a side note, the type casts you have use
Code:
(int) getLocation().getX()
are C-style casts. Where in C++ you would generally use a functional cast
Code:
int(get location().getX())
it's not a problem, but it will help when you come to learn C++ casts on pointers.
Correction: in C++ you should avoid casting whenever possible, and when a cast is unavoidable, use static_cast, dynamic_cast etc.
 

Dr_Swales

Member
Correction: in C++ you should avoid casting whenever possible, and when a cast is unavoidable, use static_cast, dynamic_cast etc.

+1, I agree, casts are horrible and your design should not include them. But they are sometimes taught in introductory C++ courses. Probably left overs from C.
 

Water

Member
+1, I agree, casts are horrible and your design should not include them. But they are sometimes taught in introductory C++ courses. Probably left overs from C.
That's too harsh, sometimes you actually need a cast. But I don't think the "functional" style casts have any advantage over C-style casts. static/const/dynamic/reinterpret casts or conversion functions should normally be used over both.
 

AngryMoth

Member
Can anyone tell familiar with php/sql tell me why this isn't working?
Code:
 public function getMaxId($table) {
		$query = $this->database->prepare("SELECT MAX(id) AS 'max_id' FROM ?;");
		$query->bindParam(1, $table);
		$query->execute();
...
For some reason $table is not binding properly. I am sure the problem is here because when I put it in the query using string concatenation and it works.
 

Zoe

Member
Can anyone tell familiar with php/sql tell me why this isn't working?
Code:
 public function getMaxId($table) {
		$query = $this->database->prepare("SELECT MAX(id) AS 'max_id' FROM ?;");
		$query->bindParam(1, $table);
		$query->execute();
...
For some reason $table is not binding properly. I am sure the problem is here because when I put it in the query using string concatenation and it works.

The first parameter in bindParam is for the data type. Change the 1 to an 's'.

http://www.php.net/manual/en/mysqli-stmt.bind-param.php
 
new practice assignment, new problems. I got everything working except one thing with this one. this program involves voting and I have to ensure the voter only votes once. I made a class called voter and within that class I have boolean "voted" set to false. what's supposed to happen is after the user enters the SSN and gets validated, the user will then vote and after they vote the voted boolean value will then be set to true. If the same user tries to vote again, a message will display that they have already voted and be sent back to the usermenu. here's my probelm, when I select the choice to vote, it goes as far as the SSN validation and then it terminates on the spot. I checked to see if it was the voter ssn validation but it's not that. here's the code I have for it:

if(vr[count].voted ==true)
{
JOptionPane.showMessageDialog(null,"you have voted already.");
usermenu();
}

if(vr[count].voted ==false)
{
input = JOptionPane.showInputDialog("please vote for a candidate");
choice = Integer.parseInt(input);
switch(choice){
case 1:
vr[count].voted = true;
cand[0].vote++;
totalvote++;
JOptionPane.showMessageDialog(null, "thank you for voting");
usermenu();
break;

case 2:
vr[count].voted = true;
cand[1].vote++;
totalvote++;
JOptionPane.showMessageDialog(null, "thank you for voting");
usermenu();
break;

case 3:
vr[count].voted = true;
cand[2].vote++;
totalvote++;
JOptionPane.showMessageDialog(null, "thank you for voting");
usermenu();
break;

default:
JOptionPane.showMessageDialog(null, "not a valid candidate");
voterchoice();
}//end choicemenu
}//end if statement

if anyone has any hints at what I did wrong then please let me know.
 

usea

Member
new practice assignment, new problems. I got everything working except one thing with this one. this program involves voting and I have to ensure the voter only votes once. I made a class called voter and within that class I have boolean "voted" set to false. what's supposed to happen is after the user enters the SSN and gets validated, the user will then vote and after they vote the voted boolean value will then be set to true. If the same user tries to vote again, a message will display that they have already voted and be sent back to the usermenu. here's my probelm, when I select the choice to vote, it goes as far as the SSN validation and then it terminates on the spot. I checked to see if it was the voter ssn validation but it's not that. here's the code I have for it:

if anyone has any hints at what I did wrong then please let me know.
Have you tried stepping through the code with a debugger? I think you will be amazed at how it reveals the way your code is behaving. You'll probably spot the problem right away with this method. Open your code in an IDE like eclipse, net beans, etc and set a breakpoint somewhere early on. Then debug the code and step through it one line at a time. Watch where the code goes.

I can't see the problem from just that one section of code. Although I don't think usermenu() and voterchoice() are doing what you think. When those functions are done executing, they'll return back to where you called them from.
 
hm this is weird. i have no idea why my iterator is iterating through objects that aren't movable.

here's the iterator code
Code:
	 Iterator i = gw.getIterator();
	 while (i.hasNext())
	 {
		 IMovable obj = (IMovable) i.getNext(); // for ever object // ERROR
		// a3.Tree cannot be cast to a3.IMovable
		 obj.move(timeElapsed); // move 
	 }

and the only objects that are part of IMovable are Tanks and Missiles, but it calls objects such as trees.

error code here
Code:
 Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: a3.Tree cannot be cast to a3.Movable
	at a3.Game.actionPerformed(Game.java:164)
	at javax.swing.Timer.fireActionPerformed(Unknown Source)
	at javax.swing.Timer$DoPostEvent.run(Unknown Source)
	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$200(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
 
Have you tried stepping through the code with a debugger? I think you will be amazed at how it reveals the way your code is behaving. You'll probably spot the problem right away with this method. Open your code in an IDE like eclipse, net beans, etc and set a breakpoint somewhere early on. Then debug the code and step through it one line at a time. Watch where the code goes.

I can't see the problem from just that one section of code. Although I don't think usermenu() and voterchoice() are doing what you think. When those functions are done executing, they'll return back to where you called them from.

I'll try a debugger like you suggested. without the if statements(i.e. when the program does run) the usermenu and voterchoice are doing exactly what I expect them to. usermenu brings the user back to the first menu after voting and,if the user makes an invalid choice, having voterchoice() there brings the user back to the input ssn validation screen.
 

usea

Member
I'll try a debugger like you suggested. without the if statements(i.e. when the program does run) the usermenu and voterchoice are doing exactly what I expect them to. usermenu brings the user back to the first menu after voting and,if the user makes an invalid choice, having voterchoice() there brings the user back to the input ssn validation screen.
Yeah, but then afterwards they will return to where you called them from. Because the call stack is a stack, so when you go someplace (by calling a function), you always return to where you left off when the function is done.

Since it looks like you just keep calling those functions, the call stack will keep growing, and eventually you'll get a stack overflow you try to vote enough times.
 

hateradio

The Most Dangerous Yes Man
hm this is weird. i have no idea why my iterator is iterating through objects that aren't movable.

here's the iterator code
Code:
	 Iterator i = gw.getIterator();
	 while (i.hasNext())
	 {
		 IMovable obj = (IMovable) i.getNext(); // for ever object // ERROR
		// a3.Tree cannot be cast to a3.IMovable
		 obj.move(timeElapsed); // move 
	 }
and the only objects that are part of IMovable are Tanks and Missiles, but it calls objects such as trees.
I don't know what you're working on, but if that's happening then gw.getIterator() returns all the objects on your map.

I don't know what gw is or how it retrieves an iterator, but make sure that it's only returning IMovables.
 
I don't know what you're working on, but if that's happening then gw.getIterator() returns all the objects on your map.

I don't know what gw is or how it retrieves an iterator, but make sure that it's only returning IMovables.

hmm. here's the suspect code
Code:
public Iterator getIterator()
	{
		return new GameObjectIterator();
	}
	private class GameObjectIterator implements Iterator 
	{
		int index;
		
		public GameObjectIterator()
		{
			index = -1;
		}
		public boolean hasNext()
		{
			if (gameCollection.size() <= 0)
			{
				return false;
			}
			if (index == gameCollection.size() - 1)
			{
				return false;
			}
			return true;
		}
		public GameObject getNext()
		{
			index++;
			return gameCollection.elementAt(index);
		}
		public void remove()
		{
			gameCollection.removeElementAt(index);
		}
	}

so i assume i have to make to make separate calls for movable etc. got it. thanks.

edit: gw is gameworld. it's the class that holds all the gameobjects such as tanks, missiles, etc.
 

hateradio

The Most Dangerous Yes Man
I don't know what you mean by separate calls, but the way I would do it is create iterables for the movable objects.

Otherwise, you'll end up having to do ugly code like "someObj is a IMobable" before calling move.
 

usea

Member
That code only shows that your iterator will iterate over every object in gameCollection. But who knows what you've put into there. Certainly not just movable things though.

Are you writing the code this way for some particular reason? I've never seen iterator code like that in Java. Can't you just use an ArrayList or something? Especially a typed collection, so you know what's in there.
 

Dr_Swales

Member

Is usermenu() meant to be where you have placed it?

What is happening in this code is after the user makes a choice, whether they have voted or not; usermenu() will be called. After usermenu() has completed the function returns to the position you called it. Which is what usea stated.
When those functions are done executing, they'll return back to where you called them from.
From that code, I would say you need to
  • Place usermenu() and voterchoice() after your if statements.
  • Make it an if-else/if-elseif so it functions as intended.
  • Default should set a flag which you check for after your switch and ifs.

That's all I can see from the code you have posted anyway. Try it yourself or clicky below.

Code:
[SPOILER]bool isValid = true;

if(vr[count].voted == true)
{
	JOptionPane.showMessageDialog(NULL,"you have voted already.");
}
elseif(vr[count].voted == false)
{
	input = JOptionPane.showInputDialog("please vote for a candidate");
	choice = Integer.parseInt(input);
	switch(choice){
	case 1:
		vr[count].voted = true;
		cand[0].vote++;
		totalvote++;
		JOptionPane.showMessageDialog(NULL, "thank you for voting");
		break;

	*SNIP SNIP*

	default:
		JOptionPane.showMessageDialog(NULL, "not a valid candidate");
		isValid = false;
	}//end choicemenu
}//end if statement

if (isValid == false)
	voterchoise();
else
	usermenu();[/SPOILER]
 
That code only shows that your iterator will iterate over every object in gameCollection. But who knows what you've put into there. Certainly not just movable things though.

Are you writing the code this way for some particular reason? I've never seen iterator code like that in Java. Can't you just use an ArrayList or something? Especially a typed collection, so you know what's in there.

it's for the tank combat program i posted awhile ago. you have to implement your own iterator.

in the end i went for something ugly like
Code:
	 Iterator i = gw.getIterator();
	 while (i.hasNext())
	 {
		 GameObject obj = (GameObject) i.getNext(); // for ever object 
		 if (obj instanceof IMovable)
		 {
		((IMovable) obj).move(timeElapsed);
		 }
	 }

it works for now.
 
I tried the code provided but that didn't work. I tried using the debugger but I couldn't make heads or tails of it only that it stopped at the first boolean if instance. I tried changing it to an int, didn't work. too tired from work, will try making the constructor to the client class public and adding (this.voted = voted) commands. if that doesn't work, I'm emailing the professor.
 
Hey everyone,

I'm going to be taking an intro level comp sci course during my next semester at college and during winter break I'd like to learn as much about programming as possible. The course is known to be pretty difficult, and I'm going to be working in java - so I was wondering if anyone could suggest any good java books to buy, or online resources to help me start thinking like a programmer.

Thank you kindly for your time.

I know I recommend Udacity a lot in this thread, but Udacity's "Intro to Computer Science" is the best programming primer in my opinion:

https://www.udacity.com/course/cs101

It's Python and not Java, but honestly the language doesn't matter as much. What's more important is learning the core concepts, which apply to pretty much any language. In my opinion, David Evans does a fantastic job at being clear, concise, and interesting in that course. And it's free, so you could always do just a bit and see if the teaching style suits you at all.
 
Fantastic, thanks. Once I finish that, would you say I'd have a decent enough background or are there other resources I should explore, maybe more java-centric?

I'm not too familiar with Java, so perhaps someone else can chime in with some recommendations.
 
how would you compute an equation like newLocation(x,y) = oldLocation(x,y) + (deltaX, deltaY) where deltaX = cos(theta)*distance and deltaY = sin(theta)*distance.

Code:
	 public void move(double time) // time in miliseconds
	 {	
		 double deltaX, deltaY; // add to new Location later
		 double timeDist = time/1000; // get the elapsed time
		 double spd = getSpeed(); // get the current speed
		 double dist = spd * timeDist; // find the distance from speed * time

		 Point oldLoc = new Point(0,0); // initialize old position
		 Point newLoc = new Point(0,0); // initialize new position
		 oldLoc.x = getLocation().x; // fill old position with location x, y
		 oldLoc.y = getLocation().y;
		 
		 deltaX = (Math.cos(Math.toRadians(90))*dist); // fill delta X and y
		 deltaY = (Math.sin(Math.toRadians(90))*dist);
		 System.out.print(deltaX);
		 
	//	 newLoc.x =  oldLoc.x + deltaX; // new location
	//	 newLoc.y = oldLoc.y + deltaY;
		 this.setLocation(newLoc);	// set new location 	 
	 }
		 
	 }

how would you add the oldloc.x and deltax values together? if i cast it with int, deltaX returns 0.

nevermind. i just took out the time/1000 to just time and objects are moving.
 
random question for java, say you want to store something into an array at random like a true or false and you create a method just for this.

Code:
public static void randommethod(){
int RM = 0;

for (int i = 1; i <50; i++)
{
RM = Math.random()*2

if(RM ==0)
{
arrayname[i]boolvariable = false;
}//end if


if(RM ==1)
{
arrayname[i].boolvariable = true;
}//end if

}//end for
}//end method
would you need to make this method return something if someone where to use it to use it for something like this?

Code:
public static void methodrequest(){
int reqval=0;

for (int i = 1; i <50; i++) {
arrayname[i].val= reqval

if(arrayname[i].boolvariable==false)
{
//insert message "denied"
}//end if


}//end for
}//end method
 

hateradio

The Most Dangerous Yes Man
^ Remember, to use the CODE tag not the QUOTE tag.

Code:
Boolean[] booleans = new Boolean[50];

for (int i = 0; i < 50; i++)
    booleans[i] == Math.random() * 2 < 1; // less than 1 is false, greater than 1 is true

Later, just test return booleans[requestVal] == false;
 

cyborg009

Banned
I'm having a strange error in Qt coding in c++. I was opening up a third window from my program and I got error about my second window. But the strange thing is that if I set the build to release the program works fine. When I only had two windows it worked fine in debug and in release.

Code:
#include "studentdialog.h"
#include "ui_studentdialog.h"

StudentDialog::StudentDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::StudentDialog)
{
    ui->setupUi(this);
}

StudentDialog::~StudentDialog()
{
    delete ui;
}




void StudentDialog::on_pushButton_clicked()
{
    newDialog = new ClassDialog();
    newDialog->show();

}
 

Slavik81

Member
I presume newDialog is a class member because you don't declare it. What else do you do with newDialog? Perhaps you're using it wrong elsewhere. Alternatively, the problem could be in the ClassDialog class itself.

I don't see anything wrong with what you posted there, though.
 

cyborg009

Banned
I presume newDialog is a class member because you don't declare it. What else do you do with newDialog? Perhaps you're using it wrong elsewhere. Alternatively, the problem could be in the ClassDialog class itself.

I don't see anything wrong with what you posted there, though.

Declare it in my second window header file. While ClassDialog has been changed since the creation of the files.

Here is second window header file
Code:
#ifndef STUDENTDIALOG_H
#define STUDENTDIALOG_H

#include <QDialog>
#include"classdialog.h"


namespace Ui {
class StudentDialog;
}

class StudentDialog : public QDialog
{
    Q_OBJECT

public:
    explicit StudentDialog(QWidget *parent = 0);
    ~StudentDialog();

private slots:




    void on_pushButton_clicked();

private:
    Ui::StudentDialog *ui;

    ClassDialog *newDialog;


};

#endif // STUDENTDIALOG_H

edit: should I just post the whole thing?
 
Hello!

Almost at the end of the semester, have a quick quest about a program I'm working on, it deals with operator overloading and complex numbers.

Right now I'm having issues converting float to string, what I want to do is take something like this:
string result1 = A + B;
use the class function for A and B (they're both class overload)

string Overload::eek:perator+(Overload otherload)
{
float real = a + otherload.a;
float imaginary = b + otherload.b;
string result = real + " + " + imaginary + " i";

return result;
}

I have tried implicit converstion, to_string(par)(I don't think the compiler has the latest standard library, it didn't find it under the std scope), but nothing wants to work.

The compiler error for the above code is:
overload.cxx:28: error: invalid operands of types âfloatâ and âconst char [4]â to binary âoperator+â
I'm guessing when I'm trying to concatenate the string with the float, it's trying to add character to the float value because real and imaginary are on the left hand side of the operands.

If I do explicit conversion, adding string(imaginary) and string(real) to the above code when assigning result, I get

overload.cxx: In member function âstd::string Overload::eek:perator+(Overload)â:
overload.cxx:28: error: no matching function for call to âstd::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(float&)â
/usr/include/c++/4.3/bits/basic_string.tcc:226: note: candidates are: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(typename _Alloc::rebind<_CharT>::eek:ther::size_type, _CharT, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:219: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:212: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, typename _Alloc::rebind<_CharT>::eek:ther::size_type, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:201: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&, typename _Alloc::rebind<_CharT>::eek:ther::size_type, typename _Alloc::rebind<_CharT>::eek:ther::size_type, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:190: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&, typename _Alloc::rebind<_CharT>::eek:ther::size_type, typename _Alloc::rebind<_CharT>::eek:ther::size_type) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:176: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:184: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.h:2067: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
overload.cxx:28: error: no matching function for call to âstd::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(float&)â
/usr/include/c++/4.3/bits/basic_string.tcc:226: note: candidates are: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(typename _Alloc::rebind<_CharT>::eek:ther::size_type, _CharT, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:219: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:212: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, typename _Alloc::rebind<_CharT>::eek:ther::size_type, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:201: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&, typename _Alloc::rebind<_CharT>::eek:ther::size_type, typename _Alloc::rebind<_CharT>::eek:ther::size_type, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:190: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&, typename _Alloc::rebind<_CharT>::eek:ther::size_type, typename _Alloc::rebind<_CharT>::eek:ther::size_type) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:176: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.tcc:184: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.3/bits/basic_string.h:2067: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]

edit: fff, decided to go the infinitely easier route and just do a void function that assigns real and imaginary to public members that I can just spit out in the client code's output stream.
 

phoenixyz

Member
Man, I got an assignment for my computer security course and somehow I don't really get what I'm supposed to do. I received a host and a port and the information
The service uses SSL and employs a symmetric prototcol, that is, client and server are exchangeable. Implement a man-in-the-middle attack by connecting twice to the service and exchanging messages.
Wat? How am I supposed to do a man-in-the-middle attack by connecting twice to it? And on top of that: it doesn't even answer to anything I send it. It just sends some 4-digit number directly after the connection has been established and then never sends any data again until I reconnect.
Can anybody make sense of that?
 

Slavik81

Member
fff, decided to go the infinitely easier route and just do a void function that assigns real and imaginary to public members that I can just spit out in the client code's output stream.
If you're using gcc, you need to pass an argument to enable C++11. It's not on by default. That flag is -std=c++11.

It doesn't matter anymore since you did it some other way, but prior to C++11, your code could look like this:

Code:
string Overload::operator+(Overload otherload)
{
   float real = a + otherload.a;
   float imaginary = b + otherload.b;
   std::stringstream buffer;
   buffer << real << " + " << imaginary << " i";
   return buffer.str();
}

Though, from a design standpoint, it's a little odd to have a operator+ that returns a string. Typically the function signature you'd use is:
Code:
Overload Overload::operator+(const Overload& otherload)

If you're interested in learning those sorts of best practices, Scode Meyers's Effective C++ covers those sorts of things. It's probably a little out of date now that C++11 is becoming widespread, though. Hopefully he publishes a 4th edition some time soon.
 

AngryMoth

Member
Hi all, I'm back with another basic web programming question.

So I'm doing pretty well with my website, about halfway through implementing the content management system, and it has occurred to me that none of the article links on my site are actually clickable yet and I don't know how to make this happen. I have programmed how to layout an article but not how to find out which article it's meant to display.

Is there some way I could do this using session variables? Like when a user clicks link it sends them to a generic article page and saves a session variable of the article id which that page can then look up?

My fear is someone is going to tell me I need to be auto generating a new unique page for every article when they are submitted to the database. That sounds like a headache.
 
Hi all, I'm back with another basic web programming question.

So I'm doing pretty well with my website, about halfway through implementing the content management system, and it has occurred to me that none of the article links on my site are actually clickable yet and I don't know how to make this happen. I have programmed how to layout an article but not how to find out which article it's meant to display.

Is there some way I could do this using session variables? Like when a user clicks link it sends them to a generic article page and saves a session variable of the article id which that page can then look up?

My fear is someone is going to tell me I need to be auto generating a new unique page for every article when they are submitted to the database. That sounds like a headache.

So if I understand the question correctly, you need to be able to load the appropriate article when a user clicks a link to it?

Easiest way is just with a GET request. They are query parameters that get placed in the URL. When your server side code gets that request, it can look at the GET request and try to retrieve the corresponding article in the database. You can then use that info to generate the page. You already have the article layout programmed, so you would just populate the necessary fields of the article with the info from the database.

GET requests just go in the url, after a "?" at the end. For example, this page ends for me with "t=475808&page=66". NeoGAF gets the request, and then looks in the database for the topic with id "475808" and page "66".

If you're using PHP, the GET request variables are just placed in the global "$_GET" array. So you can just look at that to see what someone requested.

Let me know if I didn't understand your question correctly.
 

AngryMoth

Member
So if I understand the question correctly, you need to be able to load the appropriate article when a user clicks a link to it?

Easiest way is just with a GET request. They are query parameters that get placed in the URL. When your server side code gets that request, it can look at the GET request and try to retrieve the corresponding article in the database. You can then use that info to generate the page. You already have the article layout programmed, so you would just populate the necessary fields of the article with the info from the database.

GET requests just go in the url, after a "?" at the end. For example, this page ends for me with "t=475808&page=66". NeoGAF gets the request, and then looks in the database for the topic with id "475808" and page "66".

If you're using PHP, the GET request variables are just placed in the global "$_GET" array. So you can just look at that to see what someone requested.

Let me know if I didn't understand your question correctly.
Yeah you understood my question correctly. Thanks this is really helpful. I think I get it, so I just need to append ?id=x to the url of each article. That sounds simple enough.
edit: got it working. Only took a few minutes! thanks again
 

Onemic

Member
need some troubleshooting help. My C program is supposed to roll 2 dice ranged frm 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.

For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12

//input validation
int getInt(int min, int max) {
    int retry = 1;
    int value;
    char after;
    int cc;

    do {
        printf("Enter total sought \n"
               "Range must be within [%d - %d]", min, max);
        cc = scanf("%d%c", &value, &after);
        if(cc == 0) {
            printf("bad char or 0 input, please re-enter input");
            clear();
        } else if (after != '\n') {
            printf("Error:Trailing characters, please re-ente input");
            clear();
        } else if (value < min || value > max) {
            printf("Error: value outside of range, please re-enter input");
            clear();
        } else {
            retry = 0;
        }
    } while(retry == 1);

    return value;
}

//function to clear buffer
void clear() {
    while (getchar() != '\n') {
        ; //intentional empty statement
    }
}

int throwCalc1() {
    int a = 1, b = 6, n;
    srand(time(NULL));
    n = a + rand() % (b + 1 - a);
    return n;
}

int throwCalc2() {
    int a = 1, b = 6, n;
    srand(time(NULL));
    n = a + rand() % (b + 1 - a);
    return n;
}

int throwResult(int input, int getcalc1, int getcalc2) {
    int i = 0;
    do {
        printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
        i++;
    } while(input != getcalc1 + getcalc2);
    printf("You got your total in %d throws!", i);

    return 0;
}

int main(void)
{
    int input = getInt(MIN, MAX);
    int getCalc1 = throwCalc1();
    int getCalc2 = throwCalc2();

    printf("Game of Dice\n");
    printf("============\n");
    throwResult(input, getCalc1, getCalc2);

    return 0;
}
 

usea

Member
need some troubleshooting help. My C program is supposed to roll 2 dice ranged frm 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.

For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why.
Code:
int throwResult(int input, int getcalc1, int getcalc2) {
    int i = 0;
    do {
        printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
        i++;
    } while(input != getcalc1 + getcalc2);
    printf("You got your total in %d throws!", i);

    return 0;
}
The loop in this function doesn't do anything except print and increment i. The print statement doesn't change the value of getcalc1, getcalc2 or input. But those are things being tested in the while() statement. So it's either going to loop infinitely or only execute once, depending on what you pass to the function.
 
Top Bottom