stark025 34 Newbie Poster

I just discovered that.

I wrote a new function just for it, and removed conio.h

void clrscr(){

#ifdef WINDOWS
system("cls");
#else
system("clear");
#endif
}

Also, to note again, this was to demonstrate the difference between Turbo C++ 3.0 and Visual C++ 2008. The code in Turbo C++ is really bad because it was supposed to be. This is part of my report/push towards the class using a better IDE and modern standards.

Ancient Dragon commented: for trying to get rid of turbo c in education +34
stark025 34 Newbie Poster

Come on that is trivial to find out.

First: understand why strcmp is deprecated, do you know why?

Not really.

Care to enlighten me?

stark025 34 Newbie Poster

I see that getch(), clrscr() and strcmp() are deprecated, and that I seem to miss a few much-needed prototypes.

What are the equivalents for getch() clrscr() and strcmp()?

stark025 34 Newbie Poster

Hello all,

I've recently been asked to demonstrate the difference between Turbo C++ 3.0 and Visual C++ 2008. I'm not really familiar with the current coding standards, so I've enclosed a sample of Turbo C++ code. Please point out which functions are deprecated as well as their replacements.

#include <iostream.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>

double cardNumber;
int is_looping = 1;
int loopTransact = 1;
class Billing
{
	private:
		double accountBalance;
	public:
	Billing (double openingBalance)
		{
		accountBalance = openingBalance;
		}

	void displayBalance()
		{
		cout << "Current Credit Card Balance for Card # " << cardNumber << " is: " << accountBalance << endl;
		}

	void creditToAccount()
		{
			double amount;
			char merchantID[25];
			cout << "Enter the amount to be credited: " << endl;
			cin >> amount;
			cout << endl;
			cout << "Enter Merchant ID: " << endl;
			cin >> merchantID;
			cout << endl;
			if (amount > 0)
				{
					accountBalance = accountBalance + amount;
					cout << amount << " successfully charged to credit card by " << merchantID << "." << endl;
					displayBalance();
				}
			else
				{
					cout << "Invalid amount specified. Amounts credited must be greater than 0." << endl;
					getch();
					creditToAccount();
				}
		}

	void payBill()
		{
			if (accountBalance == 0)
				{
					cout << "Transaction invalid. Account has no outstanding bills." << endl;
					return ;
				}
			double amount;
			char tellerID[25];
			cout << endl;
			cout << "Enter Teller ID: " << endl;
			cin >> tellerID;
			cout << "Enter the amount paid by client: " << endl;
			cin >> amount;
			cout …
stark025 34 Newbie Poster

Thanks. Although the answer wasn't in the JOptionPane API documentation, it was in the java.util.Array documentation, so it's all cool.

The old code was:

Object[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
			GlobalVariables.usrMonth = (String)JOptionPane.showInputDialog(null, "Input Birth Month", "Please enter your birth month: ", JOptionPane.QUESTION_MESSAGE, null, months, "January");
			if (GlobalVariables.usrMonth.equals("January")) {GlobalVariables.userMonth = 1;}
			else if (GlobalVariables.usrMonth.equals("February")) {GlobalVariables.userMonth = 2;}
			else if (GlobalVariables.usrMonth.equals("March")) {GlobalVariables.userMonth = 3;}
			else if (GlobalVariables.usrMonth.equals("April")) {GlobalVariables.userMonth = 4;}
			else if (GlobalVariables.usrMonth.equals("May")) {GlobalVariables.userMonth = 5;}
			else if (GlobalVariables.usrMonth.equals("June")) {GlobalVariables.userMonth = 6;}
			else if (GlobalVariables.usrMonth.equals("July")) {GlobalVariables.userMonth = 7;}
			else if (GlobalVariables.usrMonth.equals("August")) {GlobalVariables.userMonth = 8;}
			else if (GlobalVariables.usrMonth.equals("September")) {GlobalVariables.userMonth = 9;}
			else if (GlobalVariables.usrMonth.equals("October")) {GlobalVariables.userMonth = 10;}
			else if (GlobalVariables.usrMonth.equals("November")) {GlobalVariables.userMonth = 11;}
			else if (GlobalVariables.usrMonth.equals("December")) {GlobalVariables.userMonth = 12;}
			else {
				JOptionPane.showMessageDialog(null, "Program has encountered a validation error. Please re-enter the correct month to continue.", "Validation Error.", JOptionPane.ERROR_MESSAGE);
				getMonth();
				 }

The new code (and solution to the question) is:

public static void getMonth()
	{
			String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
			GlobalVariables.userMonth = java.util.Arrays.asList(months).indexOf(JOptionPane.showInputDialog(null, "Input Birth Month", "Please enter your birth month: ", JOptionPane.QUESTION_MESSAGE, null, months, "January"));
			GlobalVariables.usrMonth = (months[GlobalVariables.userMonth]);
				 }

My question is this: Which of the two executes faster?

stark025 34 Newbie Poster

For part of the code, I had to implement this to retrieve the month as an integer

Object[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
			GlobalVariables.usrMonth = (String)JOptionPane.showInputDialog(null, "Input Birth Month", "Please enter your birth month: ", JOptionPane.QUESTION_MESSAGE, null, months, "January");

My question is this: Is there any way to make

JOptionPane.showInputDialog(null, "Input Birth Month", "Please enter your birth month: ", JOptionPane.QUESTION_MESSAGE, null, months, "January");

return the index value in the object array

month[]

, instead of a string containing the contents of the array? Doing so would eliminate the if branches to a single statement.

stark025 34 Newbie Poster

Thanks. Changes implemented.

stark025 34 Newbie Poster

Thanks. Any other gems of wisdom to improve my code?

stark025 34 Newbie Poster

Thanks for the advice. The first post is updated with your advice. I replaced all the repetitive ifs, instead creating an Object[] array populated with the names of each month, then filling in currentmonth with the object array's elements, using the variable months as the index. It saved me 12 lines of if operations.

The new code for the ProgramOutput.java class is as below:

package _Java_Assignment_Constructors_and_JOptionPane;
import javax.swing.JOptionPane;

/**
 * @author Ray Pating
 */
public class ProgramOutput {

	public static void displayAge(int yr, int tdYr, int mth, int tdMth, int usday, int tdDay)
  	{
  		int usrYear, year, usrMonth, month, usrDay, day, outDay=0, outMonth, outYear, tempMth;
  		String pyr = new String();
  		String pmth = new String();
  		String pdy = new String();
  		int [] dayInMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
  		int tempDyMth; 
  		Object[] month_names = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"};
  		pyr = "year";
  		pmth = "month";
  		pdy = "day";
  		usrYear = yr;
  		year = tdYr;
  		usrMonth = mth;
  		month = tdMth;
  		usrDay = usday;
  		day = tdDay;
  		outDay = day - usrDay;
  		tempMth = usrMonth;
  		outMonth = (month+1) - usrMonth;
  		outYear = year - usrYear;
  			if (usrMonth-1<month&&usrDay>day)
      			{
      				outMonth = outMonth - 1;
      				tempDyMth = dayInMonth[usrMonth-1];
      				outDay = tempDyMth+outDay;
      			}
      			if ( outDay<0 )
          			{
          			outDay = getDaysInMonth(tempMth,usrDay,day);
          			outMonth = Math.abs(outMonth);
          			outMonth=(12-outMonth)-1;
          			outYear=outYear-1;
          			}
          		if (outMonth<0)
          		{	
          			outMonth=Math.abs(outMonth); 
          			outMonth=12-outMonth;
          			outYear=outYear-1;
          		}
          		if( outYear > 1 )
          			pyr = "years";
          		if( outMonth > 1 )
          			pmth = "months";
          		if( outDay > 1 )
          			pdy = "days";
          		
          		String currentMonth …
stark025 34 Newbie Poster

Hi. I am a student, and I have an report to do for our Computer Programming Fundamentals class.

We are required to demonstrate the use and function of constructors and the JOptionPane class.

I have implemented a simple age calculator using Java as my demo, and I intend to go through the code to show them what each line does, however I'd like to ask the forumers here for advice on optimizing my code so that it is:

a) smaller
b) simpler
c) well-documented (prefer this)
d) faster (prefer this over size)

I used three classes:

a Main class (http://pastebin.com/BBT0pkWt);

// Submitted by Ray Anthony Uy Pating for COMPROG1
package _Java_Assignment_Constructors_and_JOptionPane;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GregorianCalendar date = new GregorianCalendar();
      	GlobalVariables.year = date.get(Calendar.YEAR);
      	GlobalVariables.month = date.get(Calendar.MONTH);
      	GlobalVariables.day = date.get(Calendar.DATE);
		// Get current system date and time
        
		// Call primary getDate function to get user input
		UserInput.getYear();
		UserInput.getMonth();
		UserInput.getDay();
		ProgramOutput.displayAge(GlobalVariables.userYear, GlobalVariables.year, GlobalVariables.userMonth, GlobalVariables.month, GlobalVariables.userDay, GlobalVariables.day);
	}
}
/**
 * @author Ray Pating
 */

a UserInput class to gather user input (http://pastebin.com/94KRwgDi);

package _Java_Assignment_Constructors_and_JOptionPane;
import javax.swing.JOptionPane;

/**
 * @author Ray Pating

 */
public class UserInput {

	public static void getYear()
	{
		try {
			GlobalVariables.usrYear = (String)JOptionPane.showInputDialog(null, "Input Birth Year", "Please enter your birth year: ", JOptionPane.QUESTION_MESSAGE, null, null, "2010");
			GlobalVariables.userYear = Integer.parseInt(GlobalVariables.usrYear);
			if (GlobalVariables.userYear < (GlobalVariables.year - 150) …
stark025 34 Newbie Poster

This is the code that calls the function:

static int _db_get_tab(const char *key, char **ptab, char **pcol)
{
  static char tab[DB_MAX_ATTRKEY];
  static char col[DB_MAX_ATTRKEY];
  
  std::strncpy(tab, key, DB_MAX_TAB - 1);
  tab[DB_MAX_TAB - 1] = 0;
  
  // no backslash = no table = bad
  if (!std::strchr(tab, '\\')) {
    return -1;
  }
  
  // replace the backslash with a terminator
  *(std::strchr(tab, '\\')) = 0;
  
  // everything after the tab is the column
  std::strncpy(col, key + std::strlen(tab) + 1, DB_MAX_TAB - 1);
  /* since I edited sql_escape_key to allow backslashes, there now is potential
   * for a backslash to have slipped through, so we will convert it to an
   * underscore, as this was the original behavior
   */
  std::strncpy(col, sql_backslash_to_underscore(col), DB_MAX_TAB - 1);
sql_backslash_to_underscore(col), DB_MAX_TAB - 1);] value of col: %s", col);
  // terminate the column
  col[DB_MAX_TAB - 1] = 0;
  *ptab = tab;
  *pcol = col;
  
  return 0;
}

Won't making sql_backslash_to_underscore return strings break this?

stark025 34 Newbie Poster

>The thing is that the functions calling sql_backslash_to_underscore is expect a
>const char * instead of a std::string
If you don't have trouble changing the calling code, you can make a function call as : sql_backslash_to_underscore("Hello").c_str();

C-type functions which dealing with Cstrings usually let the caller code determine the output. Most of them has prototype as this:
void f(const char* input, char* output);

Wouldn't this replicate the problem earlier? I tried it and it returns blank strings again.

stark025 34 Newbie Poster

The thing is that the functions calling sql_backslash_to_underscore is expect a const char * instead of a std::string, and I created a copy as a std::string simply so that I can invoke std::replace on it. If there's any function that's identical to std::replace but can work on a const char * and doesn't leak memory, I'd be happy to implement that instead.

stark025 34 Newbie Poster

That's the thing: it works on linux but not on Windows.

Anyway fixed it, code is

static const char * sql_backslash_to_underscore(const char * key)
{
  if (!key) {
    ERROR0("got NULL key");
    return NULL;
  }

  std::string rep = key;
  std::replace(rep.begin(),rep.end(),'\\','_');
  return strdup(rep.c_str());
}
stark025 34 Newbie Poster
#include "storage_sql.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define strcasecmp _stricmp
#include <cstring>
#include <cstdlib>
#include <string> 
#include <sstream>
#include <algorithm>
#include "compat/snprintf.h"
#include "common/eventlog.h"
#include "common/util.h"

static const char * sql_backslash_to_underscore(const char * key)
{
  if (!key) {
    ERROR0("got NULL key");
    return NULL;
  }
  
  std::string rep = key;
  std::replace(rep.begin(), rep.end(), '\\', '_');
  return rep.c_str();
}

The above code returns NULL when I pass it strings like "acct\\username", "acct\\passhash" etc. What gives?