• 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

Today ill be going about writing a small game in Java, it will be a console game that reads in a text file to create a map in a 2D array ( already some what know how to do this )

I was wondering if I could get some feedback about how to logically put together my code. Right now I feel that ill need to create a class which handles a character (which will be represented in the game as a symbol or a single char) and then create classes for items.


To give you an example, this is sort of what I want to create - https://www.youtube.com/watch?v=iZNNH5eYsdE
 
I was told by my software engineering professor that it isn't good practice to continually delete items from a database and to instead "flag" it so as to not return it when querying the database. Is this generally good advice?

Also I know my input is going to be unique, but does it hurt to keep an internal ID for each item as well? Just trying to finalize my schema for my project.
 

Cromat

Member
I recommend taking the Web Dev course at Udacity:

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

You won't really learn anything about design (so the visual part of making websites) or much client side programming (so, Javascript), but it will give you a really good overview of what goes into developing a web application from the ground up. The course uses Google App Engine as well, which simplifies a lot of the maintenance parts of making a web app.

The goal throughout the course is to build some basic blogging software, and the final assignment is to create a really basic wiki. You can go fairly far after learning that basic groundwork.

You can take the course for free, the paid version just gets you a mentor and a certificate or something like that.

Wow, fantastic suggestion! Thanks
 

Water

Member
I'm on Windows 7 or Windows 8 depending on what computer I'm on, and I'm using Code::Blocks
On Windows people tend to use Visual Studio for C++ development; particularly its debugger is considered to be one of the easiest to use on the market. The "Express" version of VS is free and you may be able to get a free Ultimate version through your school as well.
There is nothing difficult about basic use of a debugger - you just set a breakpoint at some line in the code, compile and run in debug mode. After the execution breaks at your breakpoint, you step through the code, looking at how the variable values change as you go. There are some tutorials on Youtube that are from earlier VS versions but still as valid as ever. If your Code::Blocks has a debugger attached and configured, the basic idea is same there as well.
 

Hylian7

Member

Slavik81

Member
I was told by my software engineering professor that it isn't good practice to continually delete items from a database and to instead "flag" it so as to not return it when querying the database. Is this generally good advice?

Also I know my input is going to be unique, but does it hurt to keep an internal ID for each item as well? Just trying to finalize my schema for my project.

I'm curious about that first question as well. Though, I can't think of many cases in which I'd be deleting rows.

As for the second question, it seems that it's quite common to keep a generated id as the primary key for each item even if there's a natural candidate key already. The primary reason being that integer ids are small and fast to compare. String ids like email addresses or names will end up taking up a lot of space as foreign keys, and will be relatively slow to compare. (source)
 

Chris R

Member
I use a bit flag on my tables and just pull results from a view that knows to filter on that flag.

Because I'm not dealing with GBs or TBs or even bigger data sets. Makes sense to just hold onto everything in case I ever need to cover my ass or accidentally "deleted" said items.

And I also use int not null identity(1,1) primary key for my tables.

Maybe not the best way to do things, but they work for me.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Yeah, but in the spirit of "teach a man to fish", do you know how to use GDB? This probably shouldn't be that difficult to solve with a debugger.

Get the program running in GDB. After it throws the out of range exception, type

Code:
backtrace

. This will show you the 'stack trace' (what methods were being called when the error occurred, and what specific line was being executed when the error occurred). You can pick a specific method using the 'frame' command. Usually you will want to start with the lowest level method that is actually in your program and not in a library. So for example, you might type

Code:
frame 4

(or whatever frame number you wanted to look at. Once you are in a frame, you can see the value of local variables with the 'print' command. So, hypothetically, if the out of range exception was being thrown by

Code:
char x = isbn.at(i);

You change to the frame representing the checksum function, then you can examine the values causing the exception by

Code:
print i
print isbn.length()

If i >= isbn.length(), you will get an out of range exception. Then you might want to see what isbn was, by

Code:
print isbn

Since it's a string, which is a complex datatype, the print result will include some gibberish, but the contents of the string should be included. If it turn out that this ISBN is not one you wanted to process, you can use the frame command to switch to a function at a higher level in the stack and inspect what caused it to pass that ISBN. Eventually you will figure out the bug.
Aside: modern gdb (presuming the python pretty print extensions are enabled) should do a good job of displaying the string as a string.
 

Ghazi

Member
I finally have an extended period of time. I'm not too good with Math, I've missed a bunch of classes. But, a friend of mine told me Ruby on Rails was a good place to start learning. What ProgrammingGAF say? I've been enamored with programming since I did some basic stuff in Visual Basic like 7 years ago, and I want to at least try it.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I finally have an extended period of time. I'm not too good with Math, I've missed a bunch of classes. But, a friend of mine told me Ruby on Rails was a good place to start learning. What ProgrammingGAF say? I've been enamored with programming since I did some basic stuff in Visual Basic like 7 years ago, and I want to at least try it.

Python would also be a great place to start.
 

hateradio

The Most Dangerous Yes Man
Rusty, int has a ToString() method, you don't need to call Convert.ToString(). And when you're adding an int to a string, C# will actually coerce the int to a string automatically. So you can just say

Code:
var bars = Enumerable.Range(1,1000)
  .Select(x => "Bar" + x)
  .Aggregate(new StringBuilder(),
    (sb, x) => sb.Append(x))
  .ToString();
return "Foo" + bars;
Code:
var sbuilder = new StringBuilder();
var builders = Enumerable.Repeat(sbuilder, 1000);
var nums = Enumerable.Range(1,1000);
return "Foo" + builders.Zip(nums, (sb, i) => sb.Append("Bar").Append(i)).Last().ToString();

I was going to suggest a fold, but I didn't know how to do it in C#. :D

You can actually reduce your code by removing the Select (which I assume is a map) in the first one, making your second example unnecessary.

Code:
// Scala
val range = 1 to 10
range.foldLeft(new StringBuilder) { (sb, i) => sb.append("Foo").append(i) }

// C#
var range = Enumerable.Range(1,10);
range.Aggregate(new StringBuilder(), (sb, i) => sb.Append("Foo").Append(i));


Java 8 came out.

http://winterbe.com/posts/2014/03/16/java-8-tutorial/

Pretty cool and about time.
I still find it a bit weird, but that's probably because I'm used to Scala by now.
 

iapetus

Scary Euro Man
Maybe they should just go all-in and support multiple inheritance.

Hell no. Full blown multiple inheritance brings some real nastiness with it. What Java 8 has is as close as you can get to all of its benefits without exposing any of that nastiness.
 
That doesn't sound that bad. I'd take it over an intermittent problem that disappears completely whenever you compile in debug mode. A friend just fixed one of those. He works with huge piles of legacy C/C++ code written by some dude who has since retired and moved back to his farm to take care of cows, and apparently never quite learned C or C++ over 10+ years of writing them. The reason this time turned out to be that the farmerdude wanted to test the equality of some structs he wrote. And what better function to do it with than memcmp?

Oof, That sounds rough.
 

Water

Member
So is Java now on the way to becoming Scala? :)

On a totally different subject, I have finally started learning Haskell. I'm following "Learn you a Haskell", approaching the halfway mark, have just done some file reading and writing. It's amazing how cleanly and effortlessly you can do a lot of stuff in that language.

Any suggestions on what I should use when I get through the basics and want to do some graphics with Haskell? Emphasis on ease of use (including initial setup), not on performance or features. I'm dragging a friend along to learn Haskell who is strong on math but has very little previous programming experience, and I'd like to motivate him (and myself!) by building something visual with him. Platform is Windows. At minimum, I guess I'm looking for raster image output and basic graphics math facilities (2-4D vectors & matrices & functions), but direct input + interactivity would be great.
 
So is Java now on the way to becoming Scala? :)

On a totally different subject, I have finally started learning Haskell. I'm following "Learn you a Haskell", approaching the halfway mark, have just done some file reading and writing. It's amazing how cleanly and effortlessly you can do a lot of stuff in that language.

Any suggestions on what I should use when I get through the basics and want to do some graphics with Haskell? Emphasis on ease of use (including initial setup), not on performance or features. I'm dragging a friend along to learn Haskell who is strong on math but has very little previous programming experience, and I'd like to motivate him (and myself!) by building something visual with him. Platform is Windows. At minimum, I guess I'm looking for raster image output and basic graphics math facilities (2-4D vectors & matrices & functions), but direct input + interactivity would be great.
Gloss looks pretty good. I haven't really made anything with it yet (I got stuck with trying to connect my pure functions with the nasty image drawing logic). Here are some more libraries that you could use.
 

Water

Member
Gloss looks pretty good. I haven't really made anything with it yet (I got stuck with trying to connect my pure functions with the nasty image drawing logic). Here are some more libraries that you could use.
Thanks - I actually viewed that list just before asking my question and Gloss kind of stood out. Will be interested in hearing how it goes for you. I have so little time/energy to put in Haskell that it'll probably be 2-3 weeks at least before I step into graphical/realtime stuff; still plenty of things to get through in LYAHFGG. Does Gloss accommodate interactive input, BTW?
 
Thanks - I actually viewed that list just before asking my question and Gloss kind of stood out. Will be interested in hearing how it goes for you. I have so little time/energy to put in Haskell that it'll probably be 2-3 weeks at least before I step into graphical/realtime stuff; still plenty of things to get through in LYAHFGG. Does Gloss accommodate interactive input, BTW?

http://hackage.haskell.org/package/gloss-1.8.1.2/docs/Graphics-Gloss-Interface-IO-Game.html
http://hackage.haskell.org/package/gloss-1.8.1.2/docs/Graphics-Gloss-Interface-Pure-Game.html
Those two seem to be about handling input events. I found an example usage here: http://hackage.haskell.org/package/gloss-examples-1.8.0.2/src/picture/Draw/Main.hs
 
Hey guys, coming here because I'm hoping there are a few professionals who can help me;

I need to implement a printing feature into our existing MVC app hosted in Azure. The thing is the documents need to be secured, and we want minimal user interaction, so the goal is for the user(this is an internal site) to just click print, and the document gets sent to the printer(according to what the user will see). The documents themselves will be generated and stored in Azure.

I'm planning on attaching a small computer to the network/printer that will be running a windows service that will grab the document from Azure and print it.

Now, the document generation and storage part is done. The actual Windows service that prints is easy.

The part I'm struggling with is my approach to getting the document from Azure to the Windows service. Part of me feels like the service should ping Azure every 30 seconds or so to see if there are new docs, but that feels like a waste because they may just print once or twice a day. The other option is to send a message to the windows service(it doesn't NEED to be a Windows service) saying "hey, you have a doc" and then it looks up the doc and prints it.

The last part is the part I'm not sure how to approach, what technologies could I use to send a message a Windows service/something similar?
 

tokkun

Member
Hell no. Full blown multiple inheritance brings some real nastiness with it. What Java 8 has is as close as you can get to all of its benefits without exposing any of that nastiness.

How do you figure? Seems to me that Java 8's approach does expose the key element of nastiness from a programmer's perspective. If you implement multiple interfaces, and two or more of those interfaces (or their ancestors) define conflicting default methods, you have the diamond problem.
 

mltplkxr

Member
Hey guys, coming here because I'm hoping there are a few professionals who can help me;

I need to implement a printing feature into our existing MVC app hosted in Azure. The thing is the documents need to be secured, and we want minimal user interaction, so the goal is for the user(this is an internal site) to just click print, and the document gets sent to the printer(according to what the user will see). The documents themselves will be generated and stored in Azure.

I'm planning on attaching a small computer to the network/printer that will be running a windows service that will grab the document from Azure and print it.

Now, the document generation and storage part is done. The actual Windows service that prints is easy.

The part I'm struggling with is my approach to getting the document from Azure to the Windows service. Part of me feels like the service should ping Azure every 30 seconds or so to see if there are new docs, but that feels like a waste because they may just print once or twice a day. The other option is to send a message to the windows service(it doesn't NEED to be a Windows service) saying "hey, you have a doc" and then it looks up the doc and prints it.

The last part is the part I'm not sure how to approach, what technologies could I use to send a message a Windows service/something similar?
I've never done this but it sounds like you would need a client that listens on a given port, to which you send commands from your server running on Azure. If your app is on Azure, my guess is it's a .Net app so I can't help you with what to use.
So let's say you're using a client of some sort, I think it would be better to set it up on a server of your customer's infrastructure. Attaching a computer to each printer just to receive print commands sounds like a maintenamce hell.
 
How do you figure? Seems to me that Java 8's approach does expose the key element of nastiness from a programmer's perspective. If you implement multiple interfaces, and two or more of those interfaces (or their ancestors) define conflicting default methods, you have the diamond problem.

Yes and no. The diamond problem can be easily rectified in the case of interfaces. All you have to do is declare the method inside of your class and provide your own implementation. So for those that are one or the other, they can take advantage of the default methods. For hybrids, you can define the hybrid implementation in the class and call it a day. You don't have go around and remove the default implementations.
 

iapetus

Scary Euro Man
Yes and no. The diamond problem can be easily rectified in the case of interfaces. All you have to do is declare the method inside of your class and provide your own implementation. So for those that are one or the other, they can take advantage of the default methods. For hybrids, you can define the hybrid implementation in the class and call it a day. You don't have go around and remove the default implementations.

You can also, I believe, specify which one is used. And you don't have the diamond problem for constructors, which is a particularly nasty form of it.
 

Korosenai

Member
I have a c# question that is bugging me because I can't figure it out. So in a program for a add item button, I took a decimal value, and stored it to a text box as currency:

orderTextBox.Text = orderDecimal.ToString("c");

Later in the program for another button method, I need to take that number in the textbox, and multiply it with another number to find the sales tax. The following is the code I am using, along with the error:

salesTaxDecimal = decimal.Parse(orderTextBox.Text) * SALES_TAX_Decimal;

Error: "Format Exception was unhandled. Input string was not in a correct format".

Not sure what that's supposed to mean or how I'm supposed to fix it.
 

tokkun

Member
Yes and no. The diamond problem can be easily rectified in the case of interfaces. All you have to do is declare the method inside of your class and provide your own implementation. So for those that are one or the other, they can take advantage of the default methods. For hybrids, you can define the hybrid implementation in the class and call it a day. You don't have go around and remove the default implementations.

That's not really avoidance of the problem, though, it's just a method of solving it when it occurs. And there's nothing about that approach that is specific to interfaces that couldn't also be applied to classes.

In any case you still have the following problem with multiple interfaces:

-Interface X has default method do_something()
-Class C implements both Interface X and Interface Y
-A month later, Interface Y adds a default method, do_something()

Result: C no longer compiles. Programmer P gets paged when he is trying to relax on Beach B, because the build is broken.

To me, this is worse than the previous limitations of interfaces. At least before you knew that the consequence of adding to an interface was that it would break all the classes that use it. Thus, such changes were rare, and proceeded by ample warning time so the people using the interface could add their own implementations of the method before you added it to the interface. With these new default methods, it appears as if it's safe to add the default method, but in reality it's impossible for the interface designer to determine whether or not such a change will break other classes.

To me, this is the big problem of multiple inheritance: the introduction of uncertain side effects and hidden dependencies. And at least with multiple inheritance people know that this type of risk is involved, and that it matters whether you have control over the parent classes. All the code that has been written using multiple interfaces to date was written with very different expectations.

You can also, I believe, specify which one is used. And you don't have the diamond problem for constructors, which is a particularly nasty form of it.

The constructor issue is a legitimate difference, but if they don't want to deal with it, they could just restrict that if you have multiple inheritance that at most one of the superclasses is non-abstract.

There is a weird overlap now between interfaces and abstract classes, where there used to be a clear delineation.
 
I'm curious about that first question as well. Though, I can't think of many cases in which I'd be deleting rows.

As for the second question, it seems that it's quite common to keep a generated id as the primary key for each item even if there's a natural candidate key already. The primary reason being that integer ids are small and fast to compare. String ids like email addresses or names will end up taking up a lot of space as foreign keys, and will be relatively slow to compare. (source)

Part 1: I'm allowing the user to delete an item they no longer want which is why I thought keeping it hidden until they want to completely flush everything from the database is the best way to go...

Part 2: That's what I was figuring. I'm getting a unique key as a string and I figured there would be some overhead i don't want to deal with in converting each string to an int.

I use a bit flag on my tables and just pull results from a view that knows to filter on that flag.

Because I'm not dealing with GBs or TBs or even bigger data sets. Makes sense to just hold onto everything in case I ever need to cover my ass or accidentally "deleted" said items.

And I also use int not null identity(1,1) primary key for my tables.

Maybe not the best way to do things, but they work for me.

Definitely not dealing with anything close to a gb of data but that may be a good solution.
 

iapetus

Scary Euro Man
The constructor issue is a legitimate difference, but if they don't want to deal with it, they could just restrict that if you have multiple inheritance that at most one of the superclasses is non-abstract.

That doesn't solve the problem. Abstract classes can still have state that needs initialising on construction, so you still end up with exactly the same problem. Constructors are a very real problem, because both superclasses need initialising, but that can lead to a common parent class being initialised (differently) twice. And since everything has a single common superclass, that will happen.

There is a weird overlap now between interfaces and abstract classes, where there used to be a clear delineation.

That was my first thought too, but actually default methods are really just syntactic sugar. And there's still a clear delineation, in that interfaces are stateless.
 

hateradio

The Most Dangerous Yes Man
I have a c# question that is bugging me because I can't figure it out. So in a program for a add item button, I took a decimal value, and stored it to a text box as currency:

orderTextBox.Text = orderDecimal.ToString("c");

Later in the program for another button method, I need to take that number in the textbox, and multiply it with another number to find the sales tax. The following is the code I am using, along with the error:

salesTaxDecimal = decimal.Parse(orderTextBox.Text) * SALES_TAX_Decimal;

Error: "Format Exception was unhandled. Input string was not in a correct format".

Not sure what that's supposed to mean or how I'm supposed to fix it.
Can you try Convert.ToDecimal(orderTextBox.Text)?

http://hacklang.org/

I'm just learning PHP right now, what's up with this Hack?

I know it includes Collections and static typing, which already makes me interested.
Looks okay, but if there's a language I don't want to work with again it's PHP. Mostly because it lacks a lot of features that I like from other languages. Hack seems like it adds some of them, but then it wouldn't be backwards compatible in case I run into a host that can't handle it.
 

usea

Member
I was going to suggest a fold, but I didn't know how to do it in C#. :D

You can actually reduce your code by removing the Select (which I assume is a map) in the first one, making your second example unnecessary.
Oh that's awesome! I didn't even consider that. Thanks
 

Kinitari

Black Canada Mafia
Ugh, I have to do some data formatting in Javascript and while I am able to do it, I HATE the way I'm doing it now, it's close to 350 lines. I won't be happy leaving it at that, so I think I'm going to post the two object formats later and see if anyone wants to help - out of curiosity, are there gaffers who are pretty comfy using ish like underscore.js? It's what the project is working with right now, and while I am pretty comfortable with it, I really think I am under utilizing it for this problem. I want to see if I can get my code down to 100 lines or less.
 

Chris R

Member
I have a c# question that is bugging me because I can't figure it out. So in a program for a add item button, I took a decimal value, and stored it to a text box as currency:

orderTextBox.Text = orderDecimal.ToString("c");

Later in the program for another button method, I need to take that number in the textbox, and multiply it with another number to find the sales tax. The following is the code I am using, along with the error:

salesTaxDecimal = decimal.Parse(orderTextBox.Text) * SALES_TAX_Decimal;

Error: "Format Exception was unhandled. Input string was not in a correct format".

Not sure what that's supposed to mean or how I'm supposed to fix it.

You can't parse a '$' to a decimal value.

Remove it and try again.

Also, if you don't want the program throwing an error you can use TryParse instead.
 

Korosenai

Member
Can you try Convert.ToDecimal(orderTextBox.Text)?
I'll try that in a bit.

You can't parse a '$' to a decimal value.

Remove it and try again.

Also, if you don't want the program throwing an error you can use TryParse instead.

Remove the decimal.parse? I did that, using just the textbox.text and the program saw it as a string, and wouldn't let me multiply it with the decimal.

I did think about using try/catch, but the program has to use that number for a part of the calculation, it can't skip over it.

edit: Just re read and noticed you said Try Parse and not try catch. I'll do the try parse method in a bit too.
 

Godslay

Banned
I'll try that in a bit.



Remove the decimal.parse? I did that, using just the textbox.text and the program saw it as a string, and wouldn't let me multiply it with the decimal.

I did think about using try/catch, but the program has to use that number for a part of the calculation, it can't skip over it.

edit: Just re read and noticed you said Try Parse and not try catch. I'll do the try parse method in a bit too.

The decimal.parse is fine, the problem is as rhfb pointed out, that the decimal.parse is failing due to it likely getting a $ in the string that you are passing in. I was able to replicate your error in linqpad, assuming that the input string is something like
"$5.12".

Sorry for the edit, but if you wanted to clean the string you could do something like this:

Code:
 testString = Convert.ToString(testString.Replace("$", String.Empty));

As far as TryParse, it lets you test the incoming string and returns a bool depending on whether the conversion from string to decimal was successful. And it has a out parameter to which you include such as:

Code:
decimal foo;

if (decimal.TryParse(//pass in your string here, out foo))
{
    //If it's successful perform your calculations
}

Good luck!
 

Aurongel

Member
Hey CodeGAF, I'm a college Junior and i'm really struggling to break free of my dated curriculum and start working on some real code that isn't just some arbitrary homework assignment involving useless math and program structure. Problem is, I have zero guidance and no idea where to start or what makes sense to learn first. I have a solid foundation in the basics of object oriented programming and algorithms but most source code I look through online jumps way over my head and would take days to trace. Any time I try moving past simple multi-file/class programs, the code becomes very convoluted for me to understand.

I'd love to start developing my own mobile apps but I just don't know where to begin. If anyone could point me in the right direction or just list a sequence of subjects I should become educated in would be a HUGE help.
 

Chris R

Member
I'll try that in a bit.



Remove the decimal.parse? I did that, using just the textbox.text and the program saw it as a string, and wouldn't let me multiply it with the decimal.

I did think about using try/catch, but the program has to use that number for a part of the calculation, it can't skip over it.

edit: Just re read and noticed you said Try Parse and not try catch. I'll do the try parse method in a bit too.
No, remove the '$', you can't parse "$3.22" to a decimal value, while "3.22" will parse just fine. And you can keep using .Parse if you want, just pointing out other things that will parse as well.
 

Tristam

Member
My word ... I spent the last three evenings finding out why my Qt application was crashing after I incorporated a proxy model for filtering/sorting purposes. Just found out that there was a single line in a single method that I neglected to map the proxy model index back to the source model index. But that was enough to bring the app to its knees...debugging when you have no reported errors to go off of (in this case due to the app crashing) is awful.
 

Slavik81

Member
The entire model-view-delegate system for tables in Qt is extraordinarily complicated. It's very powerful, but I really hate working with it.
 
Ah, it seems my edit didn't go through . I fixed it shortly after making the post. I basically used an if statement to exclude the input "X" from the function that was giving me issues, since it's supposed to exit the program anyways.

I'm extremely thankful for the tips though, debugging is definitely an area I need to strengthen. Any recommendations for tutorials along that front? My professor is pretty terrible, and just reads the powerpoint that came with the text book for the entirety of lecture, so I've basically been teaching myself via the book, online tutorials, video tutorials, forum posts, etc. (Fortunately, I'm decent at self-learning, but about 60% of the class has dropped, if not more Lol. I'm definitely taking RateYourProfessor to hear next quarter!) So posts like yours are extremely helpful, and I really do appreciate the "teach a man to fish" mentality - since you truly do learn more in that manner.

As for the code I ended up with:

Code:
....snip....

I'm definitely enjoying programming thus far. It's incredibly frustrating at times, especially when you hit a wall, but it's also incredibly exciting/ rewarding when you finally get over that hump.


just a couple of comments--

the if statement to check if isbn is 'X' is necessary because a do..while loop doesn't check the condition until the loop has executed - so without the check, it will pass X to the checksum function, and then after returning from that it will only quit when it reaches the while() statement.

also global variables are not usually a good idea, and one of the pitfalls is right there in your code: you have the string isbn defined twice: once as a global variable, and again in the main function. this can lead to errors where for example, you have one function that acts on the global variable, and another on the local variable.

see this example:

Code:
#include <iostream>

using namespace std;

int glob = 1;

void printGlob()
{
	cout << "printglob says glob = " << glob << endl;
}

int main()
{
	int glob = 2;
	cout << "main says glob = " << glob << endl;
	printGlob();
}

and the output will be:

Code:
main says glob = 2
printglob says glob = 1

just define variables where you need them. ISBN needs to only be defined in once main, and will be passed in to the other functions.

counters like i and n should always be local variables. otherwise you might end up with an unexpected value in the counter left over from a previous function. so define them individually in the functions where you use them. if you need to pass a value from one function to another do it through the calling and return mechanisms.

lastly, i think you are using the stringstream extract operator >> to check if the ISBN is numeric? that will evaluate to true in any case where a value to fit the target, in this case an integer, is able to be extracted. so in the case of a stream where the first character is a digit, but the rest are alpha chars, symbols, or garbage, it will still return true.

you can test this out:

Code:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void checkTrue(string input)
{
	int i = 0;
	stringstream ss(input);
	cout << "input = " << input << endl;
	if (ss >> i && input.length() == 9 ) cout << "pass";
	else cout << "fail";	

	cout << endl << endl;
}

int main()
{
	string text;
	int i;

	text = "patently untrue";
	checkTrue(text); // fails

	text = "954378561";
	checkTrue(text); // passes

	text = "12maybe ?";
	checkTrue(text); // passes

	text = "9*_#@$7_X";
	checkTrue(text); // passes
}

there's also no need for the while(true) {...} loop in the validation function, as the if statement can only resolve in 2 ways: by returning true or returning false, both of which exit the function. so the statement in the while() block can only ever execute once. if you are trying to check that each character in the string is numeric try splitting the validation into a couple of checks. first check the length of the string is correct, returning false if not, and then iterate over the string checking the characters one at a time to see if they are a numeral. (other ways to do this of course, but you're probably expected to do something like that)

otherwise looking pretty good, good luck with it!
 

Tristam

Member
The entire model-view-delegate system for tables in Qt is extraordinarily complicated. It's very powerful, but I really hate working with it.

I'm inclined to agree, though I have no frame of reference, this being the first GUI framework I've used. When you first suggested I more clearly segregate my model and view, I started by trying to use the QStandardItemModel class, but even though it's supposed to support hierarchical structures, I could never make sense of its bizarre implementation when paired with a QTreeView. It took a bit of time but I learned how to create my own custom model by reimplementing key methods -- that made things a lot easier.

Now it seems that the built-in QSortFilterProxyModel is similarly weak absent reimplementation of some of its methods. For example, by default it applies only to a single column, and, for tree models, it applies recursively from the top-most nodes down. (Not the behavior that I want for it!) Fortunately there a couple of really nice guides out there showing how to extend it.
 

Big Chungus

Member
How can one validate input in C?

Trying to validating ints, doubles to make sure they're actually numbers and strings(using char arrays) being actual letters up to a certain length.
 
How can one validate input in C?

Trying to validating ints, doubles to make sure they're actually numbers and strings(using char arrays) being actual letters up to a certain length.

ints and doubles can't be anything but numbers (or inf/NaN). But you can still sanity check that the numbers are within the ranges you are expected. eg. maybe has to be positive, less than 100, etc. inf/NaN, you can use the isnan() / isinf() functions in math.h.

if you're pulling the data in from somewhere else you might do it in that stage. there's a couple of ways depending on how you read the data. eg. for scanf/fscanf, the return value is the number of items successfully read. So for instance if i want to read "%d%d%f" and the last item scanned is not a numeric, it will return a 2. Since you know the number of items you are expecting to read, if the numbers don't match there's been a failure. so you could just break it up into calls ie.

Code:
int expected = 1;
while (scanf("%f", &myfloat) != expected) {
   printf("Invalid input, enter a floating point number.\n");
   }

otherwise if the data is already in the format of a char array, and the same applies for strings, the straightforward solution is to iterate over the array, checking the value of each char is within some bounds, eg. to check if it's an alphanumeric you can see if it falls within the range specified on the ASCII table http://www.asciitable.com/ You may need some exceptions for the few symbols tucked in amongst the letters and numbers. Otherwise if you want to use regex or some other kind of pattern matching, that's not part of the C spec so will vary depending on what library you use.

Basically C being C, it depends what format your data is in, how you are getting it in to the program, what compiler and libraries you use etc. etc.
 

Fury Sense

Member
Does anyone know anything about websockets? Specifically socket.io and node.js?

I've followed a few tutorials, and tried to study some open source stuff on github. The tutorials I've seen all use different dependencies with which I am not familiar (pretty new at javascript). They work, but I don't understand them. When I try to apply my knowledge, I can't even get the most basic of tasks done. I'm super frustrated. The tutorials assume I know much more than I do, and they just give the code without explanation. The documentation on socket.io is nonexistent to boot.

Here are some of the things I've tried to study
http://www.lynda.com/Nodejs-tutorials/Nodejs-First-Look/101554-2.html
http://www.lostdecadegames.com/demos/simple_canvas_game/
http://rawkes.com/articles/creating-a-real-time-multiplayer-game-with-websockets-and-node.html <- couldn't get it to work, even downloading his "master" zip
https://github.com/clarkduvall/pixelator
https://github.com/mirceageorgescu/Real-time-canvas
https://github.com/grant/hnplays2048

This is my work (from scratch) so far http://codeshare.io/tKqOf
In it, I try to push a button to run console.log() with two messages. One from the client and one from the server. Can't figure it out, no errors, don't know what to do.

If anyone has any tips or suggestions for me, or GOOD resources (less than 3 years old), I would greatly appreciate it. For reference, I've finished half of a programming course in Racket/Scheme and have designed a handful of websites with my web developer friends. My end goal is to understand how to use sockets for duplex communications and to run code on the server as well as locally. I have a plan for a fun little multiplayer game that I could finish in a week if I could figure this stuff out.
 

Tonza

Member
Im back again with license woes.

In my github project, which is licensed under the MIT license, I would like to use a library that is under Apache 2.0 license. As far as I understand, Apache is just slightly more restrictive than MIT. Is there any problem if I upload the library files that I use with the unmodified Apache license information at the beginning of every file even though all the other code in the project is under MIT license? Currently I have not modified the library other than changing one import to match the package path of my own project. (Android project so I had to change the Resources path)

Just want to make sure I am covered. I will of course mention the library source also in the wiki and readme.
 

Kinitari

Black Canada Mafia
Does anyone know anything about websockets? Specifically socket.io and node.js?

I've followed a few tutorials, and tried to study some open source stuff on github. The tutorials I've seen all use different dependencies with which I am not familiar (pretty new at javascript). They work, but I don't understand them. When I try to apply my knowledge, I can't even get the most basic of tasks done. I'm super frustrated. The tutorials assume I know much more than I do, and they just give the code without explanation. The documentation on socket.io is nonexistent to boot.

Here are some of the things I've tried to study
http://www.lynda.com/Nodejs-tutorials/Nodejs-First-Look/101554-2.html
http://www.lostdecadegames.com/demos/simple_canvas_game/
http://rawkes.com/articles/creating-a-real-time-multiplayer-game-with-websockets-and-node.html <- couldn't get it to work, even downloading his "master" zip
https://github.com/clarkduvall/pixelator
https://github.com/mirceageorgescu/Real-time-canvas
https://github.com/grant/hnplays2048

This is my work (from scratch) so far http://codeshare.io/tKqOf
In it, I try to push a button to run console.log() with two messages. One from the client and one from the server. Can't figure it out, no errors, don't know what to do.

If anyone has any tips or suggestions for me, or GOOD resources (less than 3 years old), I would greatly appreciate it. For reference, I've finished half of a programming course in Racket/Scheme and have designed a handful of websites with my web developer friends. My end goal is to understand how to use sockets for duplex communications and to run code on the server as well as locally. I have a plan for a fun little multiplayer game that I could finish in a week if I could figure this stuff out.

Hey. I do a lot of JS stuff, but I haven't touched sockets/node yet - so I wish I could be of more help. However, one of my co-workers is a wiz at this stuff (and all stuff, it feels like) and suggested that

1. When I decide to learn sockets, sock.js is the better technology and
2. This was one of the links he told me to look at, I can't remember where the rest of them were - but one was a video. The link I gave you also assumes knowledge about backbone, so hopefully you have some experience with JS front end frameworks.

edit: from youtubing around, this video -seems- nice, and I think it talks about multiple socket libraries with node
http://www.youtube.com/watch?v=z7FcriiKY10
 
Top Bottom