• What do you need help with? v2
    3,002 replies, posted
The sizeof operator (it is not a function) gets you the size of a type or static array (array which size is known at [I]compile-time[/I]). std::string::c_str() returns a pointer of type const char*, which size is usually the size of your machine's word size (usually 32 or 64 bits these days). That means it will always send 4 or 8 bytes, regardless of your input. For input longer than 3 (or 7) characters, that means your null terminator is never sent, hence the garbage output. You want to send text.length()/text.size() + 1 characters (to accommodate for the null terminator). Also, there is no guarantee that Receive will return all of it in one call, since TCP is a streaming protocol. You usually won't run into any problems with that with really short strings like this, but when queuing longer strings you will run into problems. The best solution depends on your specific application protocol, but what you can do as of now is to simply null-terminate the buffer manually (using the return value of Receive, which is the number of bytes read) and only print a newline when you get a null byte. Alternatively, don't send the null byte at all (just send text.length()/text.size() characters), and send a newline instead, then you can just print all incoming data directly to stdout.
[QUOTE=jA_cOp;28707157]The sizeof operator (it is not a function) gets you the size of a type or static array (array which size is known at [I]compile-time[/I]). std::string::c_str() returns a pointer of type const char*, which size is usually the size of your machine's word size (usually 32 or 64 bits these days). That means it will always send 4 or 8 bytes, regardless of your input. For input longer than 3 (or 7) characters, that means your null terminator is never sent, hence the garbage output. You want to send text.length()/text.size() + 1 characters (to accommodate for the null terminator). Also, there is no guarantee that Receive will return all of it in one call, since TCP is a streaming protocol. You usually won't run into any problems with that with really short strings like this, but when queuing longer strings you will run into problems. The best solution depends on your specific application protocol, but what you can do as of now is to simply null-terminate the buffer manually (using the return value of Receive, which is the number of bytes read) and only print a newline when you get a null byte. Alternatively, don't send the null byte at all (just send text.length()/text.size() characters), and send a newline instead, then you can just print all incoming data directly to stdout.[/QUOTE] I've been trying to messing around with some stuff, but i'm not really getting any further :( Could you maybe give an example?
[QUOTE=Christianiv;28707324]I've been trying to messing around with some stuff, but i'm not really getting any further :( Could you maybe give an example?[/QUOTE] Client [cpp] #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <iostream> int main() { sf::SocketTCP client; // be consistent with capitalization of local variable identifiers // (removed some unused variables, feel free to reintroduce the "port" variable for stylistic purposes) if(client.Connect(6000, "192.168.1.14") != sf::Socket::Done) { return 1; // returning non-zero is a standard and convenient way of signaling error } else { std::cout << "Connected to IP: 192.168.1.14" << std::endl; while(true) { std::cout << "Enter text to send: "; std::string text; // declare local variables as late as possible (keeping semantics intact, of course) getline(std::cin, text); text += "\r\n"; if(client.Send(text.c_str(), text.size()) != sf::Socket::Done) { break; } } client.Close(); } return 0; } [/cpp] Server [cpp] #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <string> #include <iostream> int main() { unsigned short port = 6000; sf::SocketTCP listener; if(!listener.Listen(port)) { return 1; } std::cout << "Listening on port: " << port << std::endl; sf::SocketTCP client; if(listener.Accept(client) != sf::Socket::Done) { return 2; } std::cout << "Connection Accepted" << std::endl; char buffer[1024]; std::size_t received; while(client.Receive(buffer, sizeof(buffer) - 1, received) != sf::Socket::Disconnected) { // null-terminate and copy to stdout buffer[received] = '\0'; std::cout << buffer; } client.Close(); return 0; // this line is optional; but keep it consistent (you included it on the client, but not the server). } [/cpp] Just ask if you have any questions. (Also, you're probably aware but, the SFML/Graphics include is currently unused)
[QUOTE=jA_cOp;28707693]Client [cpp] #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <iostream> int main() { sf::SocketTCP client; // be consistent with capitalization of local variable identifiers // (removed some unused variables, feel free to reintroduce the "port" variable for stylistic purposes) if(client.Connect(6000, "192.168.1.14") != sf::Socket::Done) { return 1; // returning non-zero is a standard and convenient way of signaling error } else { std::cout << "Connected to IP: 192.168.1.14" << std::endl; while(true) { std::cout << "Enter text to send: "; std::string text; // declare local variables as late as possible (keeping semantics intact, of course) getline(std::cin, text); text += "\r\n"; if(client.Send(text.c_str(), text.size()) != sf::Socket::Done) { break; } } client.Close(); } return 0; } [/cpp] Server [cpp] #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <string> #include <iostream> int main() { unsigned short port = 6000; sf::SocketTCP listener; if(!listener.Listen(port)) { return 1; } std::cout << "Listening on port: " << port << std::endl; sf::SocketTCP client; if(listener.Accept(client) != sf::Socket::Done) { return 2; } std::cout << "Connection Accepted" << std::endl; char buffer[1024]; std::size_t received; while(client.Receive(buffer, sizeof(buffer) - 1, received) != sf::Socket::Disconnected) { // null-terminate and copy to stdout buffer[received] = '\0'; std::cout << buffer; } client.Close(); return 0; // this line is optional; but keep it consistent (you included it on the client, but not the server). } [/cpp] Just ask if you have any questions. (Also, you're probably aware but, the SFML/Graphics include is currently unused)[/QUOTE] Thanks alot it worked :D, but what is the point with the null-terminate and the sizeof(buffer) - 1? I don't really get, why you have to do it this way. It confuses me :(
so a portion of my C++ code like this: [code] char* name = new char; char* text = new char; int result; cout<<" File name: "; cin>> name; cout<<" File contents: "; cin>> text; file1 = new File(dir1, name, File::WRITE_ONLY, true); result = file1->Write(text, strlen(text));[/code] My issue is that the strlen(text) in the last line there will not return anything higher than 13. If I input a string less than 13 characters long it works fine, but anything beyond that it caps. Also, it works fine if I declare 'text' as a static array, but that is a waste of memory and presents an obvious filesize cap. Anyone know why strlen doesn't work properly here?
[QUOTE=Christianiv;28711522]Thanks alot it worked :D, but what is the point with the null-terminate and the sizeof(buffer) - 1? I don't really get, why you have to do it this way. It confuses me :([/QUOTE] sizeof(buffer) - 1 is so you can still use the last character as a null-character. And the null is appended, so std::cout can output it properly (to know where to stop). Alternatively you can also read sizeof(buffer), don't append the null and std::cout.write(buffer, received);. [QUOTE=sirbinks;28711846]so a portion of my C++ code like this: [code] char* name = new char; char* text = new char; int result; cout<<" File name: "; cin>> name; cout<<" File contents: "; cin>> text; file1 = new File(dir1, name, File::WRITE_ONLY, true); result = file1->Write(text, strlen(text));[/code] My issue is that the strlen(text) in the last line there will not return anything higher than 13. If I input a string less than 13 characters long it works fine, but anything beyond that it caps. Also, it works fine if I declare 'text' as a static array, but that is a waste of memory and presents an obvious filesize cap. Anyone know why strlen doesn't work properly here?[/QUOTE] new char will allocate memory for a single character. Using a std::string will be easier.
[QUOTE=ZeekyHBomb;28713179] new char will allocate memory for a single character. Using a std::string will be easier.[/QUOTE] Not an option unfortunately. The way the rest of the program works requires character arrays to be used here and I'm not about to go back and modify a 3,000+ line long program to use strings just so this one line will work easier.
Then allocate a number of expected characters and if the input doesn't fit, reallocate to something bigger and repeat until it fits.
[QUOTE=sirbinks;28713685]Not an option unfortunately. The way the rest of the program works requires character arrays to be used here and I'm not about to go back and modify a 3,000+ line long program to use strings just so this one line will work easier.[/QUOTE] What about using strings for getting the input, then using .c_str() to get the character array?
[QUOTE=Metroid48;28714564]What about using strings for getting the input, then using .c_str() to get the character array?[/QUOTE] Worked beautifully, thank you. Not sure why I didn't think of this myself, actually. And here I was about to start writing a getlength() method myself. Glad I checked back here one last time before I did
Line Rasterization is hard. Anyone got any ideas on how to go about with it?
im not sure if it's the best way to do it. basically I'm setting up a global stats thing (like that ranking thing in STALKER, but with real players) so whenever the player saves the game, I need to store his kills/timeplayed/whatever somewhere. i guess mysql + sqlite is the best way to do this? It's in source so it'd be using C++, and I want it to be accessed via a website
[QUOTE=Hypershadsy;28722028]Line Rasterization is hard. Anyone got any ideas on how to go about with it?[/QUOTE] [csharp] Line(int x0, int y0, int x1, int y1) { int xstep = (x0 < x1) ? 1 : -1; int ystep = (y0 < y1) ? 1 : -1; int dx = Abs(x1 - x0); int dy = Abs(y1 - y0); int error = dx - dy; finished = false; while (true) { Rasterize(x0, y0); if (finished) { break; } if (2 * error > -dy) { error -= dy; x0 += xstep; } else if (2 * error < dx) // remove else to allow diagonal steps { error += dx; y0 += ystep; } if ((x0 == x1) && (y0 == y1)) { finished = true; } } } [/csharp] Something like that should work [editline]21st March 2011[/editline] Oh, nevermind the odd loop though. It's just to get it to draw the last point in the same loop. You could replace it with while((x0 != x1) || (y0 != y1)) and drop the finished crap, but then you'd draw the last point after looping.
This works and is well tested. I used it for this: [url]http://jallenbah.co.uk/mousetracker.php[/url] [cpp]void DrawLine(int x0, int y0, int x1, int y1, Colour col) { bool steep = abs(y1 - y0) > abs(x1 - x0); if(steep) { Swap(x0, y0); Swap(x1, y1); } if(x0 > x1) { Swap(x0, x1); Swap(y0, y1); } int deltax = x1 - x0; int deltay = abs(y1 - y0); float error = 0; float deltaerr = float(deltay) / deltax; int ystep; int y = y0; if(y0 < y1) ystep = 1; else ystep = -1; for(int x = x0; x < x1; x++) { if(steep) { SetPixel(y,x, col); } else { SetPixel(x,y, col); } error = error + deltaerr; if(error >= 0.5) { y = y + ystep; error = error - 1.0; } } }[/cpp]
C++ question here.. As a weekly task right now I've been assigned to convert a fairly simple program into a class based program. However, there is one issue I'm not sure how to handle. I have a class hierarchy like so: Game -Input -Display -Logic How would I go about accessing sub-class members from another sub-class? E.g. From 'input' I want to access something from 'logic'. I am not allowed to use pointers or static methods at this time. On my phone right now, but here's somewhat what I mean: [cpp] Input::Input() { If (key) logic.DoThis() // incorrect.. How to? 'logic' declared as an object in parent class. } [/cpp]
so you want to access the members of the input class from another class without having to create a object for it? if that's it you could just use the following [cpp]someClass { friend someOtherClass; private: //do shit public: //do shit };
Ah, I wasn't aware of any 'friend' feature. I'll give it a try tomorrow afternoon, thanks.
[QUOTE=Jallen;28726369]This works and is well tested. I used it for this: [url]http://jallenbah.co.uk/mousetracker.php[/url] [cpp]void DrawLine(int x0, int y0, int x1, int y1, Colour col) { bool steep = abs(y1 - y0) > abs(x1 - x0); if(steep) { Swap(x0, y0); Swap(x1, y1); } if(x0 > x1) { Swap(x0, x1); Swap(y0, y1); } int deltax = x1 - x0; int deltay = abs(y1 - y0); float error = 0; float deltaerr = float(deltay) / deltax; int ystep; int y = y0; if(y0 < y1) ystep = 1; else ystep = -1; for(int x = x0; x < x1; x++) { if(steep) { SetPixel(y,x, col); } else { SetPixel(x,y, col); } error = error + deltaerr; if(error >= 0.5) { y = y + ystep; error = error - 1.0; } } }[/cpp][/QUOTE] Why did you write for line renderer when SFML is capable of doing it?
Don't declare it as a friend class, that's ridiculous and a silly solution. It breaks encapsulation and increases cohesion and generally means your design has a problem. Firstly, that code snippet doesn't really make logical sense... The code inside that function looks more like logic code than input code. Input code shouldn't be calling a logic function, it should just be input code... I'd do it more like this: [cpp] class Logic { private: Input inputObject; public: someSortOfLogic() { if( inputObject.keyDown() ) { //do logic } } }; [/cpp] If you want one single input object that is held in game just do this: [cpp] class Logic { Logic( Input& input ) : inputObject( input ) {} }; class Game { Game() : logic( input ) { } Input input; Logic logic; } [/cpp]
[QUOTE=sim642;28726823]Why did you write for line renderer when SFML is capable of doing it?[/QUOTE] SFML 1.6 didn't have render images.
I need some help with a regex (porting a C++ program to C#): Interp2(dp + 2, w[4], w[1], w[5]); I want to take the first argument from the call and use it on the left on an assignment, like so: *(dp + 2) = Interp2(w[4], w[1], w[5]); The argument list has a variable length and the digit behind Interp can change. How do I do this with a regex in Visual Studio or Notepad++? I tried [code]Interp{.}\({[^,]+?}, {[^\)]+?}\);[/code] and similar expressions, but I couldn't get it to match right.
My Gui is blank! :ohdear: [code]/* GambleGui.java * * This class provides a GUI for * the Gambler program. Hopefully. */ import java.awt.*; import javax.swing.*; import java.util.Scanner; public class GambleGui extends JFrame { public int MONEY = 500; public int MAX_BET = 250; public int MIN_BET = 5; public int WIN_MAX = 1500; public int CHOICE = 1; private Container container; Font meterFont = new Font("Arial", Font.BOLD, 36); SpinnerModel spin = new SpinnerNumberModel( 5, MIN_BET, MAX_BET, 1); public GambleGui() { //Gui Constructor super("Gambler"); GridLayout grid = new GridLayout(2, 2); BorderLayout border = new BorderLayout(10, 10); container = getContentPane(); container.setLayout(grid); JPanel panelNW = new JPanel(); JPanel panelNE = new JPanel(); JPanel panelSW = new JPanel(); JPanel panelSE = new JPanel(); JPanel panelBG = new JPanel(); panelNW.setLayout(new FlowLayout()); panelNE.setLayout(new FlowLayout()); panelSW.setLayout(new FlowLayout()); panelSE.setLayout(new FlowLayout()); panelBG.setLayout(grid); grid.addLayoutComponent("NW", panelNW); grid.addLayoutComponent("NE", panelNE); grid.addLayoutComponent("SW", panelSW); grid.addLayoutComponent("SE", panelSE); border.addLayoutComponent(panelBG, BorderLayout.CENTER); //Set Window Look & Feel try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println("Error setting native LAF."); } /*Convert int MONEY to a String in * order to display it as a JLabel. */ try { JLabel moneyMeter = new JLabel("£" + Integer.toString(MONEY)); moneyMeter.setFont(meterFont); panelNW.add(moneyMeter); moneyMeter.setAlignmentX(LEFT_ALIGNMENT); JLabel remaining = new JLabel ("remaining!"); remaining.setLabelFor(moneyMeter); panelNW.add(remaining); } catch (Exception e) { //Just in case some fool enters the wrong type: System.out.println("Error using the number you entered. Exception: " + e); } JSpinner bet = new JSpinner(); bet.setAlignmentX(RIGHT_ALIGNMENT); bet.setModel(spin); JLabel betHowMuch = new JLabel ("Time to Bet! How much?"); betHowMuch.setLabelFor(bet); panelNE.add(betHowMuch); panelNE.add(bet); JButton betButton = new JButton("BET"); //betButton.addActionListener(listener); panelSE.add(betButton); } } [/code]
Hi. I'm trying to sort a vector inside a class using the sort()-function, but the compiler throws an error at me. The error is: [code]Level.cpp|25|error: argument of type &#8216;bool (Level::)(Entity*, Entity*)&#8217; does not match &#8216;bool (Level::*)(Entity*, Entity*)&#8217;| [/code] This is my code for the implementation of the two function: [cpp] bool Level::Compare(Entity* entity1, Entity* entity2) { if(entity1->GetType() == ENTITY_TILE) return true; if(entity2->GetType() == ENTITY_TILE) return false; return ((entity1->GetY() + entity1->GetCollisionBox()->Top) < (entity2->GetY() + entity2->GetCollisionBox()->Top)); } void Level::Sort() { sort(this->entities.begin(), this->entities.end(), Compare); } [/cpp] Does anybody know what i'm doing wrong?
Declare the Compare function static. I'm not 100% sure if you explicitly need to use the addressof-operator (&) on it to pass it to the sort-function, but if it still errors without it, try it.
For some reason my games lecturer seems to inherit most of the classes from base or game, giving all of the clases their own draw, update and load content methods. Are there any advantages to using this instead of just having regular methods and have the main program call these methods?
[QUOTE=Tamschi;28728178]Regex: Interp2(dp + 2, w[4], w[1], w[5]); to *(dp + 2) = Interp2(w[4], w[1], w[5]); The argument list has a variable length and the digit behind Interp can change. How do I do this with a regex in Visual Studio or Notepad++?[/QUOTE] Found it: Search for Interp{.}\({.#}, {.#}\); Replace with *(\2) = Interpolation.Interp\1(\3);
[QUOTE=ZeekyHBomb;28729300]Declare the Compare function static. I'm not 100% sure if you explicitly need to use the addressof-operator (&) on it to pass it to the sort-function, but if it still errors without it, try it.[/QUOTE] Thanks! Making the method static made it work. :-)
Has anyone tried this book? I want to know if it's any good. [url]http://www.amazon.co.uk/Essential-3D-Game-Programming-Playable/dp/0123751039/ref=sr_1_1?s=books&ie=UTF8&qid=1300737944&sr=1-1[/url]
I'm not sure if it uses deprecated openGL or not, if it does it's a no-go. apart from that it seems like a good book
[QUOTE=faillord adam;28731931]Has anyone tried this book? I want to know if it's any good. [url]http://www.amazon.co.uk/Essential-3D-Game-Programming-Playable/dp/0123751039/ref=sr_1_1?s=books&ie=UTF8&qid=1300737944&sr=1-1[/url][/QUOTE] If your looking for an openGL book you should get the newest version of the "red book"
Sorry, you need to Log In to post a reply to this thread.