gretty 0 Junior Poster

Hello

I have a Container class that will allow me to store & retrieve elements from it easily by using the member variables of the elements as their key/identifier.

My problem is I am tring to store a pointer to an objects member variable, but I get a compiler error. What am I doing wrong?
PS: do you have any advice on how I could improve my Container class; such as using const correctly & whether to hide the copy constructor?

This is how I use my container class:

#include <iostream>
#include "ObjectCollection.h"

using namespace std;

// Test items
struct FoodItem
{
    unsigned int ID;
    string name;
    double price;
};

struct Order
{
    unsigned int ID; 
    unsigned int personID;   
};


int main()
{
    Collection <FoodItem*, std::string> foodCol( &FoodItem::name ); 
    Collection <Order*, unsigned int> orderCol( &Order::personID ); 
    
    // Create some test objects
    string nNames[]           = {"a", "b", "c", "d"};
    double nPrices[]          = {1.1, 2.2, 3.3, 4.4};
    unsigned int nPersonIDs[] = {6, 7, 8, 9};
    
    for (int i=0; i<4; i++)
    {
        FoodItem *f = new FoodItem() { i, nNames[i], nPrices[i] };
        Order    *o = new Order() { i, nPersonIDs[i] };
        
        foodCol.store( f );
        orderCol.store( o );
    }
    
    // Test collection
    if ( foodCol["a"]->ID == 0 ) 
    {
         cout << "Correctly retrieved a stored FoodItem by its name \n"
    }
    
    if ( foodCol[0]->name == "a" ) 
    {
         cout << "Correctly retrieved a stored FoodItem by its ID \n"
    }
    
    if ( foodCol[7]->ID == 1 ) 
    {
         cout << …
gretty 0 Junior Poster

Hello

I am experimenting with Java applets & communicating between a Servlet & an applet. I am experiencing a HTTP 501 error when I go to retrieve the input stream from my URLConnection object.

I know that the 501 error means that I am attempting to perform an action that the connection was not configured for (in my case the GET operation) but I thought my code below DOES accept input because I say conn.setDoInput( true ); .

Can someone provide me with any advice on why I cant obtain an input stream & how to fix it?

Error:

In messageServlet(): Failure: java.io.IOException: Server returned HTTP response code: 501 for URL: http://localhost:8000/TestServlet.class

My code is below (I have commented where the exception is thrown), also if you are wondering the http://localhost:8000 is a moch server I set up with a python script & that works because connecting & obtaining the output stream doesn't throw an exception.

// this code occurs in my class TextApplet::messageServlet() 
// I am attempting to send a string to my servlet class TestServlet, 
// then read a string that the servlet sends back
try
{
	URL servletUrl = new URL( "http://localhost:8000/TestServlet.class" ); 
    URLConnection conn = servletUrl.openConnection();
	
	conn.setDoInput( true );
	conn.setDoOutput( true );
	conn.setUseCaches( false );
	conn.setDefaultUseCaches (false);
	conn.setRequestProperty ("Content-Type", "application/octet-stream");			
	OutputStream out = conn.getOutputStream();
	
	out.write( message.getBytes() ); 			                  
	out.flush();
	out.close();

	// receive result from servlet
	InputStream in = conn.getInputStream(); // Exception Occurs HERE			
	BufferedReader reader = …
gretty 0 Junior Poster

No suggestions of a java HMTL parser? :(

gretty 0 Junior Poster

Hello

I am new to Java & I am trying to find ways(in built Java objects/ways) to parse HTML. Can you suggest some objects in the Java Standard Library?

I have extended the object HTMLEditorKit.ParserCallback but when parsing a web pages' source code it literally takes 2 minutes or more! But some of that is my internet right now is only getting 9kb download per second :P but nvm that.

Here is what I have done to the HTMLEditorKit.ParserCallback (overloaded the handleStartTag() & handleText() functions ):

public class SearchResultGatherer extends HTMLEditorKit.ParserCallback implements Runnable
{

	/// Class Variables:
	
	int index = 0;
	
	private Vector <SearchResult> searchResults;
	private SearchEngine          searchEngine;
	private View                  appView;
	private double                searchTime;
	private int                   searchQuantity;	
	
	/// Class Methods:
	
	public SearchResultGatherer( Vector <SearchResult> _searchResults, SearchEngine _searchEngine, View _appView )
	{
		searchResults     = _searchResults;
		searchEngine      = _searchEngine;
		appView           = _appView;
		searchTime        = -1;
		searchQuantity    = -1;

		Thread thisThread = new Thread( this );
		thisThread.start();
		// Maybe do
		// thisThread.invokeAndWait();
	}
	
         public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos ) 
	{
		for ( int i=0; i<searchEngine.targetElementInfo.length; i++ )
		{
			
			if ( t.toString().equals( searchEngine.targetElementInfo[i][0] ) )
			{
				if ( a.toString().equals( searchEngine.targetElementInfo[i][1] ) )
				{
					searchEngine.targetElementIdentified = true;
					return;
				}
				else if (i == 1)
				{
					System.out.println( "Element = " + t.toString() );
					System.out.println( "id      = " + a.toString() );
					searchEngine.targetElementIdentified = true;
					return;
				}
			}
			
		}
    }
	
	
	public void handleText( char[] arg0, int arg1 )
	{
		if ( searchEngine.targetElementIdentified )
		{
			System.out.println( arg0 );
			// System.out.println( "String …
gretty 0 Junior Poster

Hello I am new to Java & I have made a simple mortgage interest calculator.

I am looking for advice on my program such as:
- Proper java structure
- Better more efficient ways of doing what I am doing below
- Proper java format(variable names, function names)
- Are global functions a big no no in Java, should everything be in a class
- Should global functions always be public static ??

Thanks for your time :)

/*
 
   Mortgage Interest Calculator:
   	
	Hello I am looking for advice on:
	  - Proper java structure
	  - Better more efficient ways of doing what I am doing below
	  - Proper java format(variable names)
	  - Are global functions a big no no in Java, should everything be in a class
	  - Should global functions always be public static ??
 
*/


import java.util.Scanner;


public class MortageInterest
{
	
	public static void main(String[] args)
	{
		
		/// Variables
		float mortgage = 0;
		float interest = 0;
		int period = 0;
		float totalInterest = 0;
		String nPeriod;
		boolean validInput = false;
		Scanner in = new Scanner(System.in);
		
		
		
		/// Menu
		System.out.print(" *** Mortgage Interest Calculator *** \n");
		
		// Take mortgage value
		System.out.print(" Please enter the total value of the loan: $");
		mortgage = in.nextFloat();
		
		// Take interest value
		System.out.print(" Please enter the interest rate value (5.75% = 5.75): ");
		interest = in.nextFloat();
		
		// Take period calculation
		while (validInput == false)
		{
			System.out.print(" Please enter the period in which interest is calculated (in the …
gretty 0 Junior Poster

Hello

I am starting to learn both HTML & CSS for University & I have some questions about what the proper practices a HTML coder should do in terms of Website architecture:

I want to ask what is best, most conventional or the industry standards for the following:

- include css files in my HTML, is it best to do this externally, internall/embeded or inline? What is best from an employers/experienced persons POV?

- Arranging content in a HTML file? Right now I do this:
- create a header for the title of the page eg, "<h1>Sam's Page</h1>
- Arrange all elements within a table. For eg, one table element is for the navigation bar, another is for the content, another is for advertisements. This is actually something I am really lost on, the best way to arrange all the different areas on a site. Are tables a big no no to arrange my sites elements, should I be using something else(div ??)

- Any other pointers you would give someone new to coding in HTML & CSS. I'd be really greatful for any other advice :)

Thanks for reading my post :)

gretty 0 Junior Poster

Hello

I have made a simple win32 application that converts temperatures.

Problem:
I am displaying a bitmap image in a static control that is scaled using StretchBlt(). But when the application runs it goes into an infinite loop, doesn't display the bitmap & crashes.

I believe the problem is either to do with the static window where the bitmap is loaded to OR in the painting area.

To make it easy to find where the problem occurs, I think its in the Windows Proceedure function in either:
- WM_CREATE
- WM_PAINT

#include <windows.h>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include "converter.h"

using namespace std;

const char g_szClassName[] = "myWindowClass";
static HINSTANCE gInstance;
HBITMAP header = NULL;
bool convert = false;

// Functions List //
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool isEqual(double cel, double fahr);
double findFahren(double cel);
double findCel(double fahr);


int WINAPI WinMain(HINSTANCE gInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	WNDCLASSEX wc;
	HWND hwnd;
	MSG Msg;

	//Step 1: Registering the Window Class
	wc.cbSize		= sizeof(WNDCLASSEX);
	wc.style		 = 0;
	wc.lpfnWndProc   = WndProc;
	wc.cbClsExtra	= 0;
	wc.cbWndExtra	= 0;
	wc.hInstance	 = gInstance;
	wc.hIcon		 = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor	   = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(LTGRAY_BRUSH);
	wc.lpszMenuName  = NULL;
	wc.lpszClassName = g_szClassName;
	wc.hIconSm	   = LoadIcon(NULL, IDI_APPLICATION);

	// if registration of main class fails
	if(!RegisterClassEx(&wc))
	{
		MessageBox(NULL, "Window Registration Failed!", "Error!",
			MB_ICONEXCLAMATION | MB_OK);
		return 0;
	}

	// Step 2: Creating the Window
	hwnd = CreateWindowEx(
		0,
		g_szClassName,
		"Temperature Converter",
		WS_OVERLAPPEDWINDOW …
gretty 0 Junior Poster

Hello

I have a static window control & I want to make the text inside that static window centre aligned.

Is is possible to do that with a static window?

Or should I use another function?

static window:

stBox = CreateWindowEx(
              0,
              "Static",
              s.c_str(),
              WS_BORDER | WS_CHILD | WS_VISIBLE, // maybe I can put TF_RIGHTALIGN ??
              x,y,
              w+totalW+5,h+10,
              hwnd, NULL,
              gInstance,NULL);

Another question, I have a dialog using OPENFILENAME that closes when I select a file. Is there a way to make the dialog close when I select a folder instead of a file?

void doFileOpen(HWND hwnd,UINT msg)
{
    OPENFILENAME ofn;
    char szFileName[MAX_PATH] = "";
    char folderPath[MAX_PATH] = "";

    ZeroMemory(&ofn, sizeof(ofn));

    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
    ofn.lpstrFile = szFileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    ofn.lpstrDefExt = "txt";

    
    if(GetOpenFileName(&ofn))
    {   
        //CommDlg_OpenSave_GetFolderPath(hwnd,sizeof(folderPath),(WPARAM)folderPath);  // This doesn't work
        SendMessage(hwnd,CDM_GETFOLDERPATH,sizeof(folderPath),(LPARAM)folderPath);
        SetDlgItemText(hwnd,msg,folderPath);
    }
    
}
gretty 0 Junior Poster

I think it maybe my compiler also. I use dev c++, do you know how I can fix it? What I have to fix?

gretty 0 Junior Poster

Hello


I have made a simple win32 program that displays a window that has a button & a text area.

When I click the button, my program grabs the text from the text area & displays the grabbed text in a MessageBox.

My Problem:
When my program grabs the text from the text area, the text comes out as jobberish or nothing at all?

I believe the problem occurs with the code to send a message to the text area window (known as hEdit) to grab the text in it & store it in a char array.

Here is the simple code snippets where the problems occur & below that is the full program:

Window Proceedure: Creation of the controls - button & text area

case WM_CREATE: {
             hEdit   = CreateWindowEx(  
                    WS_EX_CLIENTEDGE,  
                    "Edit",  
                    "edit box example",  
                    WS_BORDER | WS_CHILD | WS_VISIBLE,  
                    10, 10,  
                    200, 100,  
                    hwnd, (HMENU)IDM_TEXT,  
                    gInstance,  
                    NULL);  
                    
             button = CreateWindowEx(
                            
                       0,
                       "Button",
                       "Capture Text",
                       WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                       110,120,
                       100,20,
                       hwnd, 
                       (HMENU)IDM_BUTTON,  // this is the custom made message sent when button is pushed
                       gInstance,
                       NULL);
                         
             }
        break;

code to grab the text from text area: this is from the windows proceedure:

case WM_COMMAND:
             
             switch(LOWORD(wParam)) {
                    // Grab text from text area if button is pushed
                    case IDM_BUTTON: 
                    {
              
                         char buffer[300];
                         SendMessage(hEdit,WM_GETTEXT,sizeof(buffer),(LPARAM)buffer);
                         MessageBox(NULL,buffer,"Captured Text",MB_OK);
                    }
                    break;
                    default:
                    break;     
             }
        break;

Full Program:

#include <windows.h>
#include <stdio.h>

// Define custom messages
#define IDM_BUTTON 1 …
gretty 0 Junior Poster

How do those hexadecimal numbers store? do they store as integer or string?

I have 3 integer variables & I want to combine them into one integer variable and as I said before each variable is an hexadecimal number

#include <iostream>

using namespace std;

int main() {

    cout << hex;
    cin >> hex;

    int a = aa;
    int b = 14;
    int c = 5d;

    // This does not work 
    int combination = (a&b&c);

    // I am trying to achieve the result where..
    // the variable combination = aa145d


    return 0;
}
gretty 0 Junior Poster

Hello

How do I combine hexadecimal numbers? For example if I have the numbers:

- aa
- 14
- 5d

How can I combine them to get : aa145d ?

gretty 0 Junior Poster

Hi

I have downloaded an editor called OceanTiger CSDesigner & it has no compiler with it. I have read the sticky posts, & I know that I could use netbeans or microsoft visual instead but I want OceanTiger because its small like Dev c++ & doesn't uses heaps of memory to run or take ages to load.

Any advice where I can download a C# compiler?

gretty 0 Junior Poster

You need to give us more of a feeling that you have really tried. Did your code produce errors? Or incorrect results? Why don't you try some simple cases like the number '4'. You should expect to see factors of 2 and 2, right? Small examples like these will help you debug the code, then you can try large numbers.

Dave

Hey listen I appreciate you looking at my post but dot say I need to prove to you I have tried, I explained that I have been racking my brain for days with numurous different functions & many many wasted hours.

Why don't you try some simple cases like the number '4'.

OFCOURSE I have tried my function, simple & hard input alike, I wouldn't have spent days rewritting testing, rewritting without testing!?

This is what my code produces for input:
- 25852

2 with multiplicity 2
3 with multiplicity 2
5 with multiplicity 2
7 with multiplicity .... crash

- 8

2 with multiplicity 3 = works

- 135

6 with multiplicity ... crash

You need to give us more of a feeling that you have really tried.

A little bit of evidence...

void factorise(bigInt I) {

     bigInt one(1); // used to increment big ints
     bigInt zero;   // find if a bigInt equals zero
     bigInt result;
     bigInt temp(I);
     bigInt P(1);
     bigInt R(1);
     bigInt mult;
     
     while (!I.lessOrEqual(one)) {  
            
           P = P.add(one); 
           temp = I;
           
           temp.divide(P,temp,R);
           
           if (!R.isEqual(zero)) { // MAY NEED TO …
gretty 0 Junior Poster

Hello

HELP :( Ok I have an assignment due in 5 days. I have done everything except for one function. This function finds the smallests factors of a positive int & it multiplicities, Have I lost you yet, dont worry because I've been lost for a week now with this function :P

Heres the funny part... we are given the algorithm!! But I cannot for the life of me understand it. I have rewritten, written, pulled my hair out for days trying to get this function to work.

I cannot seem to get this function to work. Can you take a look at my short function below & see where my algorithm is wrong?

Algorithm we have been supplied with:

An outline of the above algorithm would look something like:

// positive integer I is given
P = 1
while (I > 1)
{
P = P + 1
if I mod P != 0 go back to previous statement
// now P is the smallest prime factor of I
display P
mult = 1
exactly divide I by P as often as is possible,
assigning to I the result of each exact division,
and incrementing mult with each exact division
display mult, end line
}

An example of what the function is meant to do, if you are confused like me:

- We input a large integer: 25852
- The function …

gretty 0 Junior Poster

Hello

I am just learning Java. I have some elmentary questions. In my code below there are 3 errors that occur:
- How do I declare a string array of size 5 in Java correctly?
- How do I cin :p, take in a string array element. Ie, in C++ cin >> string, how would I write that in Java?


package similie;

import java.util.Scanner;


public class Main {
    
    public Main() {
    }
    
    public static void main() {
        
        int cAdjective, cNoun;
        int max;
        String adjective[5]; // error occurs here
        String noun[];
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter number of adjectives(must be less than 5): ");
        cAdjective = scan.nextInt();
        
        System.out.println("Enter number of nouns(must be less than 5): ");
        cNoun = scan.nextInt();
        
        for (int i=0; i<cAdjective; i++) {
             adjective[i] = scan.nextString();  // I get an error here
        }
        
        for (int i=0; i<cNoun; i++) {
            noun[i] = (String)System.in.read(); // I get an error here
        }
        
        if (cNoun >= cAdjective) max = cNoun;
        else max = cAdjective;
        
        System.out.println("max ="+max);
        
        for (int i=0; i<cAdjective; i++) {
             for (int j=0; j<cNoun; j++) {
                 System.out.println(adjective[i]+"as"+noun[j]);
             }
        }
        
        
        // do I write return 0; ??
        
    }
    
}
gretty 0 Junior Poster

I have written a new code, I think this should delete all nodes right?

void destroy(node * & L)
{
node *del = L->next;

while (del != NULL) {
L->next = del->next;
delete del;
del = L->next;
}

delete L; // Delete the head of the Linked List

}
gretty 0 Junior Poster

Hello

I am not sure if my function below will completely delete a linked list. I am worried it will delete every element of the list except for the head(first node)?

For example; If I have this linked list below

L -> 1 -> 2 -> 3 -> 4 -> NULL

Will my function delete the 1st node (1)?

void destroy(node * & L)
{

    node *temp = L;
    while(temp != NULL){
        temp = temp->next;
        delete L;
        L = temp;
    }
}
gretty 0 Junior Poster

Thanks for ur reply :)

One problem tho. Wont the code above, not delete the very last element in the linked list? Because of the 1st line within the loop -
temp = temp->next; will cause the while loop to break/stop before we get to delete head??

void destroy(node * & L)
{
     
     node *temp = L;
     while(temp != NULL){
               temp = temp->next;
               delete L;
               L = temp;              
     }

     // delete L;   //do we need to put this 
                     //in to delete the very last element??
}

Also is this(my) method better or worse?

void destroy(node * & L)
{
     
     node *del = L->next;
     
     while (del != NULL) {
           L->next = del->next;
           delete del;
           del = L->next;
     }
     
     delete L;  // Delete the head of the Linked List
}
gretty 0 Junior Poster

hello

How do I traverse & compare 2 linked lists that have different sizes without getting an error.

For example:

List1 -> 1 -> 4 -> 6
List2 -> 8 -> 3 -> 2 -> 8

// I will get an error the 4th time this loop runs
// because I will be comparing the 4th element of list2 (8) 
// to the non existant 4th element of list1 (does not exist);
//


while (list1 != NULL && list2 != NULL) {
           if (list1->data != list2->data) }
               // do sumthing
           }
}
gretty 0 Junior Poster

Please help :(

gretty 0 Junior Poster

Hello

I have 2 ways to delete a linked list, which one is correct?

If I have this linked list:


list = 1 - 2 - 3- 4

Which function will delete list correctly?
1.

void destroy(node * & list)
{
 
     while (list != NULL) {
            delete list;
            list = list->next;
     }

}

2.

void destroy(node * & list)
{ 
     delete list;
}
gretty 0 Junior Poster

Hello

I have a task to perform an addition of 2 Big Integers. Each Big Integer is stored in a linked list in reversed order. Is my add function correct?

For eg;
we have 2 Big Ints to add together

First BigInt = 245 { strored in the linked list as 5 - 4 - 2 }
2nd BigInt = 23 { strored in the linked list as 3 - 2 }

bigInt bigInt::add(bigInt J)
{ 
       // Write this function correctly.
       // You could simply insert an appropriate loop
       // where indicated below.
       int i, j, k, s;
       int carry = 0;
       node * currentp = firstp;
       node * currentJp = J.firstp;
       node * result;
       makeEmpty(result);
       
       // Insert an appropriate loop here.
       // Build up result using comp.

       while (currentp != NULL) {
              
              i = currentp->data + currentJp->data + carry;
              if (i>=10) {
                  carry = 1;
                  i = i%10;
              }
              else carry = 0;
              
              result = comp(result,i);
              currentp = currentp->next;
              currentJp = currentJp->next;
       }
      
       invert(result); // result needs to be inverted to obtain correct order of digits.
       bigInt K(result);
       return K;
}

Whole source code:

#include "bigInt.h"
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

// Definition of node
struct node
{
       int data;
       node * next;
};

/* Member functions of the class bigInt

node * comp(node * L, int x); // returns composition of L and x 
                              // (i.e. the list obtained by inserting a new node containing x
                              // at …
gretty 0 Junior Poster

Hello

I have created a simple linked list that allows me to do 3 things; create a linked list, calculate the size of the linked list & print the contents of the linked list.

Although my program crashes when I use the functions:
- int len(node *L); // return length of linked list
- void contents(node *L); // display contents of linked list

Can you help me determine why my program crashes & how to fix it?

I have a feeling it may have to do with the fact I have not set the last element of the linked lists' next pointer to NULL. If so how do I do that?

#include <iostream>

using namespace std;

struct node
{
  int data;
  node * next;
};

node * comp(node * L, int x);
int len(node * L);
void contents(node *L);

int main() {
    
    node * list;
    int n;
    int j;
    
    cout << "enter the size of the list u wish to create: " << flush;
    cin >> n;
    
    cout << n << endl;
    
    for (int i; i<n; i++) {
        cout << "enter ur data x to put in list: ";
        cin >> j;
        list = comp(list,j);
    }
    
    int m = len(list); // if I do this it crashes
    
    contents(list);  // if I do this it crashes
    
    system("pause");
    return 0;
}


node * comp(node * L, int x)
{
     // returns a pointer to the linked list obtained by inserting
     // a new node containing …
gretty 0 Junior Poster

Hello

I'm new to java & I am trying to convert a float to a string in my simple program. But I get an error on that line. Can you tell me why or what I need to do to fix it?

Maybe I haven't imported the right things or sumthing?

import java.io.IOException;
import java.util.Scanner; // must have this to take in input (cin)


public class Main {
    
    public Main() {
    }
    
    
    public static void main(String[] args) throws IOException {
        
        // Create scanner variable (cin variable)
        Scanner scan = new Scanner(System.in);
        
        System.out.println("\nWelcome to the Interest Calculator");
        
        char decision = 'y';
        
        while (decision == 'y' || decision == 'Y')   // cin >> decision
        {
            System.out .println("\nEnter loan amount:   ");
            float loan = scan.nextFloat();
            
            System.out.println("Enter interest rate: ");
            float rate = scan.nextFloat();
            
            System.out.println("\nLoan amount:         $" + loan);
            System.out.println("Interest rate:       " + (rate*100) + "%");
            
            float interest = (loan*rate);
            
            System.out.println("Interest:            $" + interest);
            
            System.out.println("Continue? (y/n): ");
            decision = (char)System.in.read();
        }
    }
    
    public String alter(float n) {
        /// Pre: variable n must be of type float
        /// Post: return loan amount as a string with commas inserted
        
        String number = Float.toString(number); // ERROR HERE convert float to string;
        
        number.length();
        
        return number;
    }
    
}
gretty 0 Junior Poster

I was in ur position, every tutorial makes it sound like you need this and that to start programming. And i'm trying to learn java & i'm finding the same thing again.

All you need is this:

- Dev C++
(This is a compiler - meaning an editing program to wirte the code in & compile it.)

Search dev C++ on google, download it. Ur done. There are heaps of other compilers out there, u can even use notepad to code, not so much compile BUT Dev C++ is the easiest, smallest(in download size) & most efficient when stating off.

A few pointers, once you have installed & opened the Dev C++ program.

- Create a new source file ( this is a c++ document, u know that because the file name will end in .cpp)
- This file is where u write ur code. In order to run ur program( the code u have written in the source file) you need to click the button compile, ie compile your code.
- Then u can click run, to, obviously run ur program & thats pretty much it.

If u want to create a project, make sure u select the type as "console application/project", this is best for beginners.

Thats pretty much it but make sure u look at a c++ hello world tutorial to know what to write in the source file

gretty 0 Junior Poster

Hello

I am studying for my exam & I came across this question that is stumping me.

class X
{
   public:
      X();
   private:
      int x1, x2;
};

class Y : public X
{
    public :
     Y();
   private:
     int y3;
}  // the class Y does not end in an '};' but just a } maybe thats a typo or its meant to be like that

Question:
Describe the kinds of operations which would be implemented in function Y();

I know what constructors are & I recognise that X(); & Y(); are default constructors BUT I have never seen this before class Y : public X

What does that mean?

Does it mean,an object of class Y can be accessed by an object of class X because the class Y is a public 'element/function?' of class X??

gretty 0 Junior Poster

Pop each element. Check if there are equal matching braces/brackets...

So do you mean:

/* Algorithm
1. store each character of s into stack <char> letters
2. check if letters.top() == "[{(<" (open bracket) - if yes - int open++;
3. check if letters.top() == "]})>" (closed bracket) - if yes int close++;
4. letters.pop();
5. if letters.empty() { if (open == close) { return true; }
    else return false;
*/
bool balanced(string s)
{

     stack <char> letters;
     int open = 0;
     int close = 0;
     
     for (int i=0; i<s.length(); i++) {
          letters.push(s.at(i));
     }
     
     while (!letters.empty()) {
           if (isOpen(letters.top())) {
                open++;
           }
           else if (isClose(letters.top())) {
                close++;
           }
           
           letters.pop();
     }
     
     if (open == close) {
         return true;
     }
     else return false;

}
gretty 0 Junior Poster

Hello

I want to attempt a freelance c++ job/project for the skills & experience but do you think there are any jobs out there for my skill level?

I have been learning programming for 8 months, only know c++,
& I only know the basics, arrays, vectors, pointers, stacks ,lists,queues, header files, classes, overloading. templates, recursion.

I dont have any experience with API, nor MFI(is that right...is it MCI....see I dont even know the name :P)

So I guess I am asking for some advice:
Would you say...
- "Ur in waaay over ur head. Dont even bother taking on a c++ freelance job, tyke"
- "You may find some jobs out there that just require your skill level"
- "You have plenty of skills to do a c++ freelance job"
- other.

gretty 0 Junior Poster

Hey I am trying to make console apps too, but I ahven't got very far :P

Would you feel comfortable sharing your code here so others can learn how to create a console app?

ps, um yeah sorry I dont have anything constructive to add to ur prob lol, making console apps is hard :(

gretty 0 Junior Poster

Hello

Can you assist me in developing my algorithm?

I have to do this:

Write a C++ function balanced that uses a stack to check that all brackets in a string are balanced.

For eg:

This is a balance string:
This (string) has (balanced {brackets[(now)]} [thanks])

This string is not balanced:
This [[string has (bad} brackets]>)

I am strugling thinking of a way of doing this using stacks.

My idea so far is:

Check each character of a string:
- if the character is any of these "[{(<" then (open.push(1)) - where open is a stack of integers.
- else if the character is any of these "]})>" then (close.push(1)) - where close is a stack of integers.
- else do nothing

If we reach the end of the string & open.size() == close.size() then the string is balanced
, if not then the string is not balanced.

This is the only way I can think of, although it does not really utilise the features of a stack, because I could just use int counters to replace the stacks open & close & it would still work.(i am just counting open & closed brackets).

Any ideas how I could use stacks (LIFO characteristics) to find if a string is balanced? :)

gretty 0 Junior Poster

Well it is definately wrong.

The reason is that the method say it will return an object of set, but -1, EXIT_SUCCESS etc is an integer so it will not compile.

The return from a function is based on what will happen later and how bad it is.

For example consider say [icode]set divide(const set& other)[/icode]
in the above. [multiply is a bad choise since 0 * a number is ok.
What options do we have, well we could have
this->num=5 other.num=2 that would be a slight problem, since 5/2 in the set of integers is 2. Maybe you need a warning? Or we could hvae other.num=0 and things have gone very wrong.

There are four main options:

(a) set an other variable : status and put the status of the result but always return a valid output.
(b) set the output (if it is a class) to some-predefined error status.
(c) throw an exception
(d) exit the code.

Like you said, I am trying to stop the function if I encounter an error

But I am unsure how to stop the function becuase of its type, if it was an int function I'd just use return -1;

The above code was a simple example; this is what I am really doing:

set set::unions(int x) const
{
    // pre : none
    // post : returns the union of this set and x (if x in range)

    int setRange = getUpperRange();

    // …
gretty 0 Junior Poster

Hello

I am unsure of the correct way to make this function below(multiply) stop if a condition is true?

The reason why is because of the function type, its not an int, string, void etc, I am unsure how to stop a function whos type is the class name?

Do I use...
return;
return -1;
return EXIT_SUCCESS;
return FAIL;

#include <iostream>

using namespace std;

class set {
      
      public:
             set multiply(const set &other) const;
             
      private:
              int num;
};

set set::multiply(const set &other) const
{
    
    if (num == 0) {
        cout << "Function 'multiply' stopped \n";
        return -1; // is this the correct way to stop/end this function or should I use return; or return EXIT_SUCCESS;
    }
    
}
gretty 0 Junior Poster

Hello

Can you tell me why my for loop below doesn't show all the elements contained in a stack (stacks size = 3).

It only shows the top 2 elements when it shoudl show all 3?

Also another question, is there a way to show the contents of a stack without deleting the top element(or any elements).

Ie, If I have a stack with a size of 10, how do I output/refer to the 3rd element of that stack? I cant use stack.at(3) or stack.top(3)?

#include <iostream>
#include <stack>

using namespace std;

int main() {
    
    stack <int> list;
    
    list.push(20);
    list.push(10);
    list.push(2323);
    
    cout << list.size() << endl;
    
    for (int i=0; i<list.size(); i++) {      // should display all elements in stack right? but only displays the 1st 2??
        cout << "List " << i << "= " << list.top() << endl;
        list.pop();
    }
    
    /*     This works , ie , displays all elements of the stack
    for (int i=list.size(); i>0; i--) {
        cout << "List " << i << "= " << list.top() << endl;
        list.pop();
    }
    */
    
    system("PAUSE");
    return 0;
}
gretty 0 Junior Poster

Hello

Would anyone like to share their tips & tricks for debugging functions & whole programs in C++.

I find I suck at debugging :P & really dont look forward to having to go through my functions again to see if there are any loopholes etc so if anyone could provide some tips & tricks it would be really helpful.

I have searched alot and there aren't many places to find advice on how to do it & I find it really tedius :P

From my experience I would offer this advice:
- DEBUG AS YOU GO - Every time you write a function or every hour or sumthing like that. Going over your whole program is a b***h, lol, :P

- When debugging functions that take in input - list all the possible input that someone may enter then test ur function with it, make sure it either works or it outputs "invalid input" or etc, so that it doesn't crash.

Please share any other advice for debugging :)

gretty 0 Junior Poster

read the structure here

Your code contains a few little bugs. For example: int dd = atoi(d.c_str());

Ah I see, to display the day I can just say the below & to get the week number I can just use some maths to get it.

cout << tm.tm_yday << endl; // eg today will be 279 (out of 365 days)

But one problem, :P again:

I am implementing the above code, but it is displaying todays values not the given date?? So when I write cout << tm.tm_yday with the input date 01/01/09, it should output 1 but it outputs 279 (todays day number).

int getWeek(int a, int b, int c) {  // where a = day, b=month, c=year

                // a = 1, b = 1, c = 2009 (01/01/2009)
	struct tm tm; // do not user a pointer here!
	memset(&tm, 0, sizeof(struct tm)); // set everything to 0s

	tm.tm_year = c - 1900;
	tm.tm_mon = b-1; 
	tm.tm_mday = a;
	time_t t = mktime(&tm); 

	cout << tm.tm_yday << endl;  // should output - 1  but it outputs todays day number - 279

}
gretty 0 Junior Poster

Cool thanks, :)

One thing tho, with your code, you said it should return the day of week, will my code below(your code altered :) ) give the week number not day of the week?

void getWeek(string& date) {
     
    char buffer[4];  
    
    struct tm tm; // do not user a pointer here!
    memset(&tm, 0, sizeof(struct tm)); // set everything to 0s
    
    // 
    string d = date[0] + date[1];
	string m = date[3] + date[4];
	string y = date[6] + date[7];
	
	int dd = atoi(d);
	int mm = atoi(m)-1;
	int yy = atoi(y);

    tm.tm_year = yy - 1900;
    tm.tm_mon = mm; // where 0 = Jan, 1 = Feb, etc
    tm.tm_mday = dd;
    time_t t = mktime(&tm); // Am I correct that  this will return the day of the week?
    // if so how would I  get the week number of the year
    
    // to get the week, would it be
    strftime (buffer,4,"%W",tm);  // instead of tm should it be 't'?
    
    int week = atoi(buffer);

}
gretty 0 Junior Poster

very similar, but you could fill in a struct tm with the date then call mktime() to fill in the rest, including the day-of-week. Make sure you memset the struct tm with all 0's before you start or mktime() will return an error condition.

Thanks :)
I'm very new to this libray (ctime & time) would you be able to suggest how to code this?

Is this what you mean? :)

void getWeek(string date) {
     
                time_t rawtime;
	struct tm * date;      // date is a string tho?? 'dd/mm/yy'
	char buffer[4];

                mktime(date);          // correct syntax??

	time ( &rawtime );
	timeinfo = localtime ( &rawtime );

	strftime (buffer,4,"%W",date);   
	
    week = atoi(buffer);     
}
gretty 0 Junior Poster

Hello

I am making a function that takes in a date (dd/mm/yy) & returns what week number of the year the date occurs on.

For eg;
If I enter: 01/01/09 then the week number of that year will be 1
If I enter: 04/09/09 then the week number of that year will be 35

I have this function I altered that gives the week number of the current date ONLY.
Is there a way to alter the below function where it takes in a parameter of a date(dd/mm/yy) & returns what number week that is of the year??

Ie, alter this function to take in a given date & return what week number that would be.

I hope that makes sense :P

void getWeek(int& week) {
     
    time_t rawtime;
	struct tm * timeinfo;
	char buffer[4];

	time ( &rawtime );
	timeinfo = localtime ( &rawtime );

	strftime (buffer,4,"%W",timeinfo);   // '%W' = week number of the year, eg 1/1/09 == 1
	
    week = atoi(buffer);     // convert char to int
}

for example

void getWeek(string& date) {  // date format 'dd/mm/yy'
     
    time_t rawtime;
	struct tm * timeinfo;
	char buffer[4];

	string d = date[0] + date[1];
	string m = date[3] + date[4];
	string y = date[6] + date[7];
               
	time ( &rawtime );
	timeinfo = date; // is that  correct????

	strftime (buffer,4,"%W",timeinfo);   // '%W' = week number of the year, eg 1/1/09 == 1
	
    week = atoi(buffer);     // convert char to int
}
gretty 0 Junior Poster

Hello

My program takes in a number & uses a recursive function to display that number backwards. eg input = 473, output= 374.

I have to submit the program for marking, but they always throw in some curve ball test to make sure that your program will work for all cases.

Can you take a look at my program and tell me if it will work for all numbers? Or can you see an exception when this algorithm wont work?

Our tutor actually gave us the answer :P but mine is different & I am trying to be sure my code works for all numbers/cases so I dont loose a mark again :P

// My way of doing it
void reverseDigits(int x)
// displays the int x with its digits in reverse order.
// recursive algorithm
{
    if (x>1) {        // will this work for all numbers??
        cout << x%10;
        reverseDigits(x/10);
    }
    
}

// My tutors example 
void reverseDigits2(int x) {
     
    cout << x%10;
    
    if (x>10) {
        reverseDigits2(x/10);
    }
}

whole program:

#include <iostream>
using namespace std;

void reverseDigits(int x);
void reverseDigits2(int x);

int main()
{
   int number;
   cout << "Enter a number : " << flush;
   if (cin >> number)
   {
       cout << number << " reversed is ";
       reverseDigits(number);
       cout << endl;
   }
   else
      cout << "Invalid input " << flush;
   system("pause");
   return 0;
}

// My way of doing it
void reverseDigits(int x)
// displays the int x with its digits …
gretty 0 Junior Poster

Yes sorry I am back again lol :P

Thanks for the help so far but yes I have changed, AGAIN :P, how I am doing it lol. I read firstPerson's reply & I am going to use his advice, use infile.get.

But I am back at the problem of changing a string/char to a float. How can I do this?

I cant really make x a char because remember I am reading float numbers from a text file, for eg;

layout = Week number - purchase 1 - purchase 2 - purchase 3 - purchase n

for eg.
1 2.4 1.4 // taking in fractional numbers
32 1.4 2.7
50 8.45 2.56

maybe I could make x a char array of 4 elements, char x[4] ??

So my major problems are:
- how to change x to a float (from a char array or string)
- how to take in number that are more than one character long(float numbers not ints) eg 12.04 using infile.get(char x))

string x;

while (infile.get(x)) {

           if  (x=='\n') {   
                cout << "count advanced\n";
                count++;          
                pCount = 0;
           }    
           else {
                pur[count][pCount]= x;  // here I need to change x from a char to a string if x is a char array of 4 elements does [B]atof[/B] still work??
                pCount++;
           } 
     }
gretty 0 Junior Poster

Okay I need help with this second part please.

1. Find words in dictionary which match pattern
The user is prompted to enter a word pattern which contains ? for missing letters, the word pattern is converted to lower case and the program displays words in array which match pattern. The words are displayed in alphabetical order. See required prompts and output in the sample run.


Can anyone generate the code for me according to the information and code I posted above?

Thanks.

EDIT:
This is what it should look like:

Crossword Helper 

 1 : Check if word is in dictionary 
 2 : Find words in dictionary which match pattern 
 3 : Quit 

2 
Enter word pattern with ? for missing letters 

y??ht?w????

yachtswoman

Do you go to Mq Uni? :) we just did that assignment

gretty 0 Junior Poster

thanks guys

Although I am back again with a problem, I have totally overhauled the whole function but it still uses a 2d array.

In the below code, the variable 'count' is never advanced, ie, the if statement never gets called but it should whenever we get to a line break.

float x;

while (infile >> x) {

           if  (x==(char)'\n') {    // this event never happens but it should
                cout << "count advanced\n";
                count++;          
                pCount = 0;
           }    
           else {
                pur[count][pCount]= x;
                pCount++;
           } 
     }

The file I am reading is arranged like this

Week number purchase 1 purchase 2 purchase 3 purchase n

for eg.
1 2.4 1.4
32 1.4 2.7
50 8.45 2.56

gretty 0 Junior Poster

Also, from experience. I see that using 2D array to store information
from a file does not always work well. The program might not set
the file content it to proper location. I would suggest to use 1D array.

If 2D is really needed , then use 1D array, and copy it into 2D array.

Thanks :), I agree, 2d arrays are tedius, I wanted to test myself by using one(2d array) in a program but I dont really HAVE to use a 2d array. I am probably going to use a vector because it will be alot more efficient (memory-wise) & alot easier

gretty 0 Junior Poster

Thanks, lol, I realise now I can do this so I have changed it. But now I have run into another problem.

I am tring to convert x, which is a float into an int. but I get this error

cannot convert `float' to `const char*' for argument `1' to `int atoi(const char*)'

Is there a way I can fix this without changing x to a 'const char' or 'char', ie, keep it as a float.

while (infile >> x) {
           count = atoi(x);   // error occurs here again
           
           while (x!=(char)'\n' || count2<=25) {
                 pur[count][count2]= x;
                 count2++;
           }
           count2 = 0;
           count++;
     }
gretty 0 Junior Poster

Improper use of an array,

pur[count] = x; // Error

Try,

while (infile >> x) {
          if(count2==25) {
                count2=0;
                count++;
          }
      pur[count][count2]= x;
     count2++;
   }

oh, so are you saying that I cannot store 25.5 in where x is - pur[x][]? Is that not possible when I am using a 2d array?

so I cant cant go ...
cout << pur[x];
& it will output 25.5

gretty 0 Junior Poster

hello

I am reading a text file & trying to store some information into a 2d array.

My problem is when I go to store a piece of data into the 1st row (1d area ?:P) I get this error

error:

incompatible types in assignment of `float' to `float[25]'

For eg, I want to store 25.5 where x is
pur[x][];

My function:

float pur[53][25];   // Purchases Array [week number][purchase no.1, p2, pn...]

ifstream infile;
float x;
int count = 0; 
int count2 = 0;

while (infile >> x) {
           pur[count] = x;   // error occurs here
           
           while (x!=(char)'\n') {
                 pur[count][count2]= x;
                 count2++;
           }
           count2 = 0;
           count++;
     }
gretty 0 Junior Poster

Thanks. silly me :P

gretty 0 Junior Poster

hello

I have some code that loops & takes in a number then should store it in an array.

My problem is that for some reason, the program only stores every 2nd number entered?

while (!cin.fail() && cin>>purchase) {   // while a correct input is input
           
           cin >> purchase;                 // enter recent purchase
           pur[nWeek][counter] = purchase;  // store recent purchase in relevent array element
           cout << "purchase put in array element " << counter << "\n";
           counter++;
     }

Whole function

void enterPurchase(float pur[][25], int nWeek, int counter) {
     
     float purchase = 0;
     
     while (!cin.fail() && cin>>purchase) {   // while a correct input is input
           
           cin >> purchase;                 // enter recent purchase
           pur[nWeek][counter] = purchase;  // store recent purchase in relevent array element
           cout << "purchase put in array element " << counter << "\n";
           counter++;
     }
     
     for (int i=0; i<counter; i++) {
         cout << "Purchase No." << (i+1) << ": $";
         cout << pur[nWeek][i] << "\n";
     }
     
     cout << pur[nWeek][2] << endl;
}
gretty 0 Junior Poster

change to

void enterPurchase(float pur[][25], float nWeek, float counter);

That solved the 1st issue :) thanks

The second issue still seems to be occuring still