Open Side Menu Go to the Top

11-17-2015 , 06:33 AM
Quote:
Originally Posted by Wolfram
but then he's no longer using C, he's using C++.
So? C is a subset of C++, lots of places/people code primarily in C but use a few C++ features. In fact that is pretty much standard. I can tell you for certain that Microsoft and Intel do exactly that. They aren't the only places. If you were concerned about linking your code to un-mangled C libs/modules that is easy to do. Bringing in C++ exception handling will increase the size of your code. In an embedded environment you probably want to avoid this like the plague. In a Linux/windows type environment not a problem.
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread
11-17-2015 , 07:18 AM
Quote:
Originally Posted by adios
I would recommend using C++ exception handling since C is a subset of C++. Google is your friend regarding exception handling. You could have your functions throw exceptions when errors are detected.
Seems like the typedef enumeration linked earlier itt would be pretty good for this allowing you to avoid C++. Probably depends on how deeply you want to learn custom error handling haha.
Programming homework and newbie help thread Quote
11-17-2015 , 11:02 AM
Quote:
Originally Posted by adios
So?
He asked: "What is the best practice for handling errors in C?".

If you give him an answer in C with some C++ features, he's no longer programming in C. He's programming in C++.

Quote:
Originally Posted by adios
C is a subset of C++
Exactly! The answer needs to be constrained to the subset, not the superset.

Last edited by Wolfram; 11-17-2015 at 11:18 AM.
Programming homework and newbie help thread Quote
11-17-2015 , 11:12 PM
Quote:
Originally Posted by econophile
What is the best practice for handling errors in C?

I've been writing an expression interpreter that works by recursive descent, and errors could arise in one of several nested functions. Each error will call a function that will set the global int errno to some nonzero number, and the main function will print an error message if there is one.

But I also want to stop evaluating the expression after the first error occurs. Does that mean that I have to put in error checks in all of the helper functions (sometimes more than one per function)? Is there a better way to do this?

For example, one of the functions looks like this:

Code:
double BoolExp(void)
{
	double Value;
	
	if (!errno)
		Value = Equivalence();
	while (Look == '&' || Look == '|' && !errno) {
		if (Look == '&') {
			Match('&');
			Value = (Equivalence() && Value);
		} else {
			Match('|');
			Value = (Equivalence() || Value);
		}
	}
	return Value;
}
Here an error could arise each time Equivalence() is called. It's also possible that error could arise when BoolExp is called since it is defined recursively (indirectly). (Although I guess I could add a check to prevent BoolExp from being called again if there has already been an error.)

Yes, in C you would put an error check on each function. I've used macros in the past to help with this:

Code:
#ifndef errChk
#define errChk(fCall) if (error = (fCall), error < 0) \
{goto Error;} else
#endif
You can put an Error label at the end and have it as a way to clean up any memory that was allocated.
Programming homework and newbie help thread Quote
11-18-2015 , 09:56 PM
Quote:
Originally Posted by adios
I would recommend using C++ exception handling since C is a subset of C++. Google is your friend regarding exception handling. You could have your functions throw exceptions when errors are detected.
Unless something has changed since I stopped programming in C (which is possible), C is not a strict subset of C++.
Programming homework and newbie help thread Quote
11-19-2015 , 06:22 AM
Strict subset no but the things that don't complie in C++ are considered poor programming practice.
Programming homework and newbie help thread Quote
11-19-2015 , 02:26 PM
working on a chat program. started super basic but have added timestamps to messages and, since adding an authentication method, storing passwords and whatever else seems too much of a hassle atm, each client appends their message with the IP address their socket uses. Kind of like a screen name but more confusing!

The issue is that there's an arraylist of connections and I'm not sure how to test if someone has disconnected, if that could be handled in the client, or what, so the arraylist is never cleared of closed connections.

Like, I know I can stop the running of the client program when someone closes the chat window with:

JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO SE);

But I would also possibly like a way to close the socket as well when that happens. Is that possible (on the client I assume)? Or do I need to check that each of my sockets is still open as I iterate through them to send messages (from the server)?
Programming homework and newbie help thread Quote
11-19-2015 , 03:00 PM
The OS handles closing any sockets that are still open when the program exits.

On the server side just continue as normal while catching exceptions when read/write to socket.
Programming homework and newbie help thread Quote
11-19-2015 , 03:09 PM
My server is still trying to send messages to anyone that's connected. So I can hav one person connected but the software tries to send to however many that have connected since it started
Programming homework and newbie help thread Quote
11-19-2015 , 07:01 PM
maybe this makes more sense with code.

Code:
clientOutputStreams = new ArrayList();
        try {
            ServerSocket serverSock = new ServerSocket(5000);
            
            while(true) {
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                clientOutputStreams.add(writer);
                
                Thread t = new Thread(new ClientHandler(clientSocket));
                ...do thread stuff
My assumption now is that I need to write some code for the ClientHandler inner class that checks to see if it's closing. If it is, it somehow removes its own writer reference from the clientOutputStreams arraylist.

But I'm not quite sure how to do that. Like, I think I understand that I need to add a finally block at the end of run method that handles that, but I don't quite get how to make sure I remove the correct reference or instance.

Does that make sense? Or was it already clear?
Programming homework and newbie help thread Quote
11-19-2015 , 07:35 PM
Figured it out, wooo!

moved printwriter creation to the inner class and kept the arraylist in the outer class. Allowed me to remove the connection when the thread ends.
Programming homework and newbie help thread Quote
11-20-2015 , 11:27 AM
Quote:
Originally Posted by adios
Strict subset no but the things that don't complie in C++ are considered poor programming practice.
As I said, it's been a while since I used either language in earnest, but when I did, the classic example of one of the difference is:

sizeof('a')

which gives different results in C and C++ and not something I'd regard as poor programming practice.
Programming homework and newbie help thread Quote
11-20-2015 , 04:29 PM
Quote:
Originally Posted by codeartisan
As I said, it's been a while since I used either language in earnest, but when I did, the classic example of one of the difference is:

sizeof('a')

which gives different results in C and C++ and not something I'd regard as poor programming practice.
I would. When you coded in C when did you apply sizeof IE when was it useful? It is used a lot in C and C++ code btw.

Last edited by adios; 11-20-2015 at 04:40 PM.
Programming homework and newbie help thread Quote
11-27-2015 , 10:06 PM
Hi all, first time posting in here so hope i don't mess it up.

Very new to programming, C# / .NET, and currently in my first few weeks of an internship of sorts.

Not sitting in front of my code so might have to use a little pseudo code here, apologies.

I've been assigned a little project to build an app that finds the file paths of all text files in a given destination folder plus all root folders and loads them to an array.
It then needs to cycle through this array, read each text file and lastly build a table. All text files are in this format:
Code:
Fname: John
Sname: Smith
Age: 25
ID: 123
Ref: R11
Date: 01022013

Fname: Paul
Sname: Smith
Age: 28
ID: 143
Ref: R12
Date: 01052013

Fname: Brian
Sname: Jones
Age: 25
ID: 223
Ref: R23
Date: 01022011

.....
I have the methods build to load the array with file paths and built a method to split the contents of each file using Regex.split ": ". This gives me an array "string [] wordList", containing basically a list of each word like so:
Code:
Fname
John
Sname
Smith
Age
25
ID
123
Ref
R11
Date
01022013
...
Ive created a data table with the six headings and am now trying to access the relevant elements of the array, assign them to local variables and then add a row to the table. Tried using a switch first, then a for loop:
Code:
String fname;
String sname;
String age;
String id;
String ref;
String date;

for (int i=1; i<=11 && i<=wordList.Lenght; i+=2)
   {
      if(i==1)
       {
          fname = wordList[i];
       }
else if(i==3)
       {
          sname = wordList[i];
       }
......

//add row to table (fname, sname, age,.....)
i=1;
   }
This throws an exception after the first if statement.

Am I going about this all wrong? ie should I be loading the table totally differently (what should I be googling ). If not can anyone tell me what's wrong with my loop?

Apologies for the TLDR, thought it best to give as much info as possible.

Any replies greatly appreciated
Programming homework and newbie help thread Quote
11-28-2015 , 12:37 AM
By "build a table" do you mean a System.Data.DataTable?

There is no reason to assign the array members to local variables and no reason to put an if statement in your loop. DataRow supports assignment to columns via integer index. You want to loop half as many times as the length of the array and assign each of them to the appropriate index, like this:

Code:
DataRow row = yourTable.NewRow();
for(int i = 0; i < wordlist.Length / 2; i++) {
    row[i] = wordlist[i * 2 + 1];
}
yourTable.Add(row);
I don't know why your code throws an exception, other than Length being mistyped it looks OK. To figure that out I'd need the exception type, message and the exact line that throws it.
Programming homework and newbie help thread Quote
11-28-2015 , 12:51 AM
Importing the file into an array first is a weird way of doing it though. Here's how I'd do it:

Foreach file in your file list:
- Create a new DataRow
- Open the file for reading (there's a StreamReader constructor that takes a filename, check this out).
- While (ReadLine != null)
--- If the line is empty (use string.IsNullOrWhiteSpace), ignore it.
--- Split it on ": ". The resulting array should be length 2. If not, throw a FormatException explaining the problem.
--- Use the row's dictionary-style assignment, i.e. row["key"] = "value", here it should be row[splitArray[0]] = splitArray[1];
- Close the file
- Add the row to the table

I can expand on any of these if you'd like.

Last edited by ChrisV; 11-28-2015 at 12:59 AM.
Programming homework and newbie help thread Quote
11-30-2015 , 12:59 PM
java compiling question:

I read a book that said you should try to keep your classes and java files separate, so I made a classes folder. I have a project with two java files (both have 1-3 inner classes), and if I compile to the source folder with the java files, I get all the appropriate class files.

However, if I follow the book's instructions and compile to a separate directory, I only get class files for the java file I'm calling javac on.

So: javac -d ../classes mainClass.java - only gives me mainClass and mainClass inner class files
but: javac mainClass.java - gives me mainClass/inner and supportClass/inner class files

What gives? Do I need to package them up for it to work properly?
Programming homework and newbie help thread Quote
12-01-2015 , 06:51 PM
Quote:
Originally Posted by ChrisV
Importing the file into an array first is a weird way of doing it though. Here's how I'd do it:

Foreach file in your file list:
- Create a new DataRow
- Open the file for reading (there's a StreamReader constructor that takes a filename, check this out).
- While (ReadLine != null)
--- If the line is empty (use string.IsNullOrWhiteSpace), ignore it.
--- Split it on ": ". The resulting array should be length 2. If not, throw a FormatException explaining the problem.
--- Use the row's dictionary-style assignment, i.e. row["key"] = "value", here it should be row[splitArray[0]] = splitArray[1];
- Close the file
- Add the row to the table

I can expand on any of these if you'd like.
Hey man, sorry for the delay replying. I've been sick for a few days. Should be back in work tomorrow so will be looking over your two replies in more detail then. Both much appreciated btw.

If it wasn't too much hassle an elaboration on the quoted part above would be great also. There are more than one data rows per text file so that's where i'd get a bit lost.
Being new to C# among a team of experts means i'll take any help offered

Edit: Forgot to answer your question. I just meant I had a constructor built defining a data table columns and headings matching those from the text files

Last edited by DublinMeUp; 12-01-2015 at 06:58 PM.
Programming homework and newbie help thread Quote
12-06-2015 , 07:41 AM
Quote:
Originally Posted by Noodle Wazlib
However, if I follow the book's instructions and compile to a separate directory, I only get class files for the java file I'm calling javac on.

So: javac -d ../classes mainClass.java - only gives me mainClass and mainClass inner class files
but: javac mainClass.java - gives me mainClass/inner and supportClass/inner class files

What gives? Do I need to package them up for it to work properly?
Not entirely sure (been a while since I've messed with Java) but would expect that you'd need to add the classes folder as include path. javac probably does not know where to look for the other files that may or may not be referenced in mainClass.
Programming homework and newbie help thread Quote
12-06-2015 , 08:00 AM
Quote:
Originally Posted by DublinMeUp
There are more than one data rows per text file so that's where i'd get a bit lost.
Your initial code from earlier is essentially an endless loop unless there are some other control statements missing. Setting i=1 at the end of each iteration will lead to reading line 1 over and over again.
Not sure where an exception creeps in there, either. Might be something important missing in that block that happens earlier.

If you want to stick to splitting up into arrays you want to split on several levels. While not particularly pretty, it can work.

For each file, split by empty line (effectively: two new line characters in succession - ignoring potential white spaces in between), then you got the records.
Loop over those and split them as you did before. Beware that many split off components as with your earlier loop will have a new line character at the end of it, so strip accordingly (String.trim is your friend there).

Tip: Do not muddle with your control variable inside loops - variable i in your example - you will most likely end up with a severe headache down the line.

A more elegant way would be to follow ChrisV's approach, and just use the empty line as separator between data sets.
His algorithm can be adjusted to write data sets when you encounter an empty line, and close the file when you encounter an end of file. You may or may not have to write the last data set when encountering end of file. Keep that in mind.
Programming homework and newbie help thread Quote
12-07-2015 , 01:39 PM
Hey guys, very new around these parts. I want to start learning coding... where should I start with this? Someone directed me to the Treehouse website and as I'm really new I wanted to check if I'm going down the right track.

If you could recommend me anything else I should look at that would be greatly appreciated, My end goal is to build what seems a complex website to me but maybe it won't to those who have been doing this stuff for sometime.

Any help would be good, just keep in mind I'm very very new
Programming homework and newbie help thread Quote
12-07-2015 , 01:48 PM
if you're willing to learn, go the Odin Project route
Programming homework and newbie help thread Quote
12-07-2015 , 02:20 PM
I had success with Udacity. Try the Intro to Programming Nanodegree.
Programming homework and newbie help thread Quote
12-07-2015 , 02:46 PM
Thanks guys will check these out
Programming homework and newbie help thread Quote
12-07-2015 , 02:56 PM
Quote:
Originally Posted by Noodle Wazlib
if you're willing to learn, go the Odin Project route
Definitely heard good things about this.

For general programming classes there are a ton of open courseware sites (MIT Open Courseware, Udemy, quora, edX).

All have varying levels of "freeness" and quality of materials.
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread

      
m