# C/C++ Thread



## Cromewell

Please post any questions relating to C/C++ here. Please also specify which you are using and external libraries, if any, you are using. (Note: Visual C++ is slightly different than ANSI C++, generally your code will work between the two but certain functions you may want to use in VC++ wont be available in ANSI).

You can also use this thread to post code you wish to share.


----------



## fastdude

EDIT: My question has been resolved by an in-the know friend.
Just to start the thread off:

#include <iostream>
using namespace std;
void main()
{
  cout << "Hello computerforum!" << endl;   cout << "Welcome to the C++ thread" << endl; }


----------



## Troncoso

I suppose this can also be the C# thread? As I just started a class in said language and I feel I'm really going to enjoy it and expand beyond the classroom.


----------



## Dropkickmurphys

Troncoso said:


> I suppose this can also be the C# thread? As I just started a class in said language and I feel I'm really going to enjoy it and expand beyond the classroom.



You could probably put C# in the .NET thread as it is a .NET language  (or it is nowadays)


----------



## Cromewell

I would probably put C# in with the .NET stuff. It's usually going to be managed code that fits better there. That said, if you think your stuff fits better here or there go with that one, it can always be moved if necessary.


----------



## Dystopia

fastdude said:


> EDIT: My question has been resolved by an in-the know friend.
> Just to start the thread off:
> 
> #include <iostream>
> using namespace std;
> void main()
> {
> cout << "Hello computerforum!" << endl;   cout << "Welcome to the C++ thread" << endl; }



Looks good, but the way I am learning, you shouldn't be mixing the lines. Also I use Visual C++ so it is a tad different.

But, that should look like:


> #include <iostream>
> using namespace std;
> 
> void main() //actually I have a different string of stuff I have yet to learn what it means, but apparently Visual requires slightly different stuff
> 
> {
> cout << "Hello computerforum!" << endl;
> // I actually go and seperate them like this too, only the cin goes under cout, but thats prefrence. I think.
> cout << "Welcome to the C++ thread" <<endl;
> 
> return 0; //You forgot this part, I think without it either, the program will just close, or, you won't have the message saying "press any button to continue......."
> }



Monday I started learning how to set up a table of info, today I am supposed to be learning how to finish that.


----------



## Cromewell

31!m!n80r said:


> Looks good, but the way I am learning, you shouldn't be mixing the lines. Also I use Visual C++ so it is a tad different.
> 
> But, that should look like:
> 
> 
> Code:
> 
> 
> #include <iostream>
> using namespace std;
> 
> void main() //actually I have a different string of stuff I have yet to learn what it means, but apparently Visual requires slightly different stuff
> 
> {
> cout << "Hello computerforum!" << endl;
> // I actually go and seperate them like this too, only the cin goes under cout, but thats prefrence. I think.
> cout << "Welcome to the C++ thread" <<endl;
> 
> return 0; //You forgot this part, I think without it either, the program will just close, or, you won't have the message saying "press any button to continue......."
> }
> 
> Monday I started learning how to set up a table of info, today I am supposed to be learning how to finish that.


You're right, you should put everything on its own line for readability, the couts can be chained without really hurting how easy it is to read. However, the return call isn't needed in fastdudes post (or your updated code) because the main function is a void.



Your main probably looks more like:


		Code:
	

int main(int argc, char *argv[])

Depending on what you are doing you may (or may not) want/need to return a value to the calling process to indicate whether your code succeeded or not. I'm pretty sure the standard says main always needs to return a value.


----------



## Dystopia

Cromewell said:


> You're right, you should put everything on its own line for readability, the couts can be chained without really hurting how easy it is to read. However, the return call isn't needed in fastdudes post (or your updated code) because the main function is a void.
> 
> 
> 
> Your main probably looks more like:
> 
> 
> Code:
> 
> 
> int main(int argc, char *argv[])
> 
> Depending on what you are doing you may (or may not) want/need to return a value to the calling process to indicate whether your code succeeded or not. I'm pretty sure the standard says main always needs to return a value.



Yup, that's my main all right.


Today I learned how to effectively use the <iomanip> function. Also worked more on the <cmath>.


----------



## Dystopia

Installed Visual Basic 2010. Currently learning how to use a switch instead of a if function.


----------



## Cromewell

31!m!n80r said:


> Installed Visual Basic 2010. Currently learning how to use a switch instead of a if function.


It's a pretty useful block when you need to test 1 variable for a series of different values but if you have a complex check you need to use if statements. You can put multiple values in the same case if they all need to be treated the same. The break statements are also important because wihout them all the code below will execute, as seen in the second code block below.


		Code:
	

switch (var) {
  case <value>: //if var = <value> code1 runs
    code1;
    break;
  case <value2>, <value3>: //if var = value2 or var = value3 code2 runs
    code2;
    break;
  default: //this is like an else on an if statement
    code3;
}




		Code:
	

switch (var) {
  case <value>: //if var = <value> code1 runs
    code1;
    break;
  case <value2>, <value3>: //if var = <value2> or var = <value3> code2 and code3 will run
    code2;
  default:
    code3;
}


----------



## Dystopia

Cromewell said:


> It's a pretty useful block when you need to test 1 variable for a series of different values but if you have a complex check you need to use if statements. You can put multiple values in the same case if they all need to be treated the same. The break statements are also important because wihout them all the code below will execute, as seen in the second code block below.
> 
> 
> Code:
> 
> 
> switch (var) {
> case <value>: //if var = <value> code1 runs
> code1;
> break;
> case <value2>, <value3>: //if var = value2 or var = value3 code2 runs
> code2;
> break;
> default: //this is like an else on an if statement
> code3;
> }
> 
> 
> 
> 
> Code:
> 
> 
> switch (var) {
> case <value>: //if var = <value> code1 runs
> code1;
> break;
> case <value2>, <value3>: //if var = <value2> or var = <value3> code2 and code3 will run
> code2;
> default:
> code3;
> }



Yeah, that's what I learned too.

I'm up to the for/while/do-while loops. Really like that, no more having to restart the program to test every single input validation!

I've also learned how to make my own functions.


----------



## Troncoso

You learned things in a different order than I did. We wrote our own functions from the start. Programming is fun to me until I get to classes. Then I get sad


----------



## Dystopia

Troncoso said:


> You learned things in a different order than I did. We wrote our own functions from the start. Programming is fun to me until I get to classes. Then I get sad



Yeah, my instructor said from now on he wants us to use our own functions. Took me a bit to get how to do it, especially having several variables.

I enjoy programming too...and why do you get sad in class? I like it in class, where I can learn how to do new things. Although if I get a project that takes some time, I just do it on my laptop, so I can leave early.


----------



## brian

31!m!n80r said:


> Yup, that's my main all right.
> 
> 
> Today I learned how to effectively use the <iomanip> function. Also worked more on the <cmath>.



Hah, we just learned about that yesterday. So far I am enjoying the class, so far its stuff I already know but it helps to reinforce.


----------



## Dystopia

^I really like the iomanip myself.


----------



## Cromewell

31!m!n80r said:


> Yeah, my instructor said from now on he wants us to use our own functions. Took me a bit to get how to do it, especially having several variables.
> 
> I enjoy programming too...and why do you get sad in class? I like it in class, where I can learn how to do new things. Although if I get a project that takes some time, I just do it on my laptop, so I can leave early.



I think he meant he gets sad when he has to build classes in programming. You'll get to them later in your course work.


----------



## Troncoso

Cromewell said:


> I think he meant he gets sad when he has to build classes in programming. You'll get to them later in your course work.



he's correct. I mean using classes in your program and creating objects and instances of those objects...when I was using gamemaker this stuff was way more fun. But in the applications that we made that used classes, they felt completely unnecessary, so I never really got a feel of their importance.


----------



## muhammad.arif09

*for C++/c student*

for student of C++/C 
www.cs50.tv
check it and reply must


----------



## Dystopia

Ok, I am supposed to write a program that will calculate the new total of a loan, by the end of each year. I am supposed to do the calculation each month, but display it each year. A function MUST be created for calculating the new balance (ie. new balance = old balance + old balance*rate - monthly payment). I can't make the stupid program calculate that in a function!! Here is the code I have written. Let me know if you guys need more comments:



		Code:
	

// lab11.cpp : Defines the entry point for the console application.
//
//Adam Holthaus, steve05

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;


double balance(double, double, double, double);
int _tmain(int argc, _TCHAR* argv[])
{
	//Declaring variables
	double monthlyrate, monthlypay, m1, m2, m3, m4, rate, oldb, newb, loan, years, numpayments, apy, month, yrs;
	month = 1;
	newb = 0;	
	//Getting loan info
	cout <<"What is the value of the loan? $";
	cin >> loan;
	oldb = loan;
	cout <<"For how long will you have the loan? ";
	cin >> years;
	cout <<"What percentage is your APY? ";
	cin >> apy;
	//Getting monthly payment
	numpayments = years*12;
	monthlyrate = apy/1200;
	rate = monthlyrate+1;
	m1 = pow(rate, numpayments);
	m2 = monthlyrate*m1;
	m3 = m1-1;
	m4 = m2/m3;
	monthlypay = m4*loan;
	//Finding new balance
	for(yrs = 1; yrs <= years; yrs++)
	{
		while(month < 12)
		{
		newb = balance(newb, oldb, monthlypay, rate);
		month++;
		}

		cout <<newb <<endl;
	
	}

	return 0;
}


//newbalance.cpp calculates the new balance each month for one year, for lab11
//Adam Holthaus, steve05

#include "stdafx.h"
//Function
double balance(double newb, double oldb, double monthlypay, double rate)
{
	

	newb = oldb + oldb*rate - monthlypay;
	return newb;
}


I got the monthly payment right. That works. But the calculation screws up. I am using VisualStudio 2010. If you want to run it in your own compiler that is not VS, exchange my "main line" with yours, and remove the #include "stdafx.h" code.

Also, I have the code all together here, but in my compiler, I have the function separated the way I am supposed, I know that's not the issue.

This is just homework, not a test, and I just need help figuring out the function part.

Anybody figure out what I am doing wrong?


----------



## Cromewell

I'm guessing this is for simple interest (i.e. you have to pay off the interest accrued each year) instead of compound interest.

Check how you are handling the interest. Some of the calculations don't look right to me around your monthly payment comment around line 30.


----------



## ScottALot

Brand new to programming other than Visual BASIC and HTML... is there a list of programs that's like half-required to download to start programming in C/C++ [and JAVA]?


----------



## Cromewell

ScottALot said:


> Brand new to programming other than Visual BASIC and HTML... is there a list of programs that's like half-required to download to start programming in C/C++ [and JAVA]?



An IDE helps but all you really need is a compiler, you can technically write the code in a plain text editor and use the command line to compile. For C/C++ on Windows DevC++ is ok, visual studio is as well. There may be other editors/compilers out there but those are the 2 I've used.

For Java a lot of people like Eclipse.


----------



## Troncoso

I have to say. Programming in C/C++ in linux has been a treat to me.especially since gedit has built in sytax highlighting and auto tabbing. And all you need to compile is gcc and g++ which I think are included. If now they are easy to install


----------



## Dystopia

Cromewell said:


> I'm guessing this is for simple interest (i.e. you have to pay off the interest accrued each year) instead of compound interest.
> 
> Check how you are handling the interest. Some of the calculations don't look right to me around your monthly payment comment around line 30.



Hmmm, I'll check it out. If found that when I try to call a function, it doesn't work, as in, the code within the function doesn't seem to be executed.


----------



## Cromewell

This is some sample output I get when I run your code:


> What is the value of the loan? $100
> For how long will you have the loan? 5
> What percentage is your APY? 10
> 198.709
> 198.709
> 198.709
> 198.709
> 198.709


The function is doing something or it wouldn't retun any value.


----------



## Troncoso

Can someone maybe tell me why this wouldn't work right:



		Code:
	

#include <stdio.h>
#include <math.h>

int main()
{
	printf("This program will accept a whole number and return it's factorial.\n Please enter a whole number: ");
	
	int number;
	scanf("%d", &number);
	
	while (number % 1 != 0)
	{
		printf("This value is not a whole number. please type a whole number: ");
		
		scanf("%d", &number);
	} 
	
	int total = number;
	int count;
	
	for (count = number - 1; count > 0; count--);
	{
		total = total * count;
	}
	
	printf("The factorial of %d is %d.\n", number, total);
	
	getchar();
	
	return 0;
}


When I run it, it just goes from the first printf statement to the last, as if it's not even doing the while loop or the for loop...No matter what I change I get the same outcome.

EDIT: Okay, I got it calculating the factorial, but the reason it seems to be skipping the while statement, is because when you type a decimal (ex. 5.2) it just truncates the .2 so it proves true. My problem is inputting a letter. When I input the letter 'd' and hit enter it says "The factorial of 6598644 is 0" I have no idea how it gets that number.


----------



## Cromewell

I think D is giving you weird values because you are then effectively using uninitialized memory.

For your loop, check the very start for your error, no complier will report it as a syntax error but it is.


----------



## Troncoso

So basically I should go ahead and initialize the variable before I get the user input?


----------



## Cromewell

You should really be validating the user input before trying to use it but it's never bad to initialize your variables.


----------



## Troncoso

Well now you've confused me. That's what I am trying to do. That's what the while statement is for, to validate the value. I'm trying to figure out why, no matter wat I type in, the while function accepts the value and doesn't catch my exception handler.


----------



## Cromewell

Oops didn't see it, instead of using number % 1 try using the actual typing function in ctype.h (cctype for c++ headers). You'll also have to clear the input stream of the invalid characters or it will keep trying to read them in.

edit: I hate input in C...I think the best way is to read the input as a string and then try to convert it to the type you need. I've always had trouble trying to clear out the unread characters.

edit2: something like this:


		Code:
	

...
	int number;
    char input[250];
	
	fgets(input, sizeof input, stdin);
	
	while (sscanf(input,"%d",&number) != 1)
	{
		printf("This value is not a whole number. please type a whole number: ");
		
		scanf("%s", &input);
		sscanf(input, "%d", &number);
	} 
...


----------



## Troncoso

oh wow. Thank you. just a question about sscanf:

the first argument, that's the max size of the string right? why did you use input as the argument.


----------



## Cromewell

sscanf(const char * str, const char * format, ...)

The ... in the function call represents user managed parameters instead of compiler. This is how you can say sscanf(string, "%d %s %d", num1, str1, num2) or sscanf(string, "%d",num1) and have both run on the same code.

The first parameter to sscanf is the string you want to scan, the second parameter is what you are looking for and the n parameters after are the variables you want to store the results in.


----------



## Troncoso

Okay, I tried that and I get the same outcome:



		Code:
	

[email protected]:~/Documents$ ./fact
This program will accept a whole number and return it's factorial.
Please enter a whole number: 5.2
5! = 120.


[email protected]:~/Documents$


I should be getting the error message for 5.2. When typing letters it works, but not decimals.


----------



## Cromewell

True enough, scanf (and any derivative) will try and return the requested type based on the pattern you are looking for. Since 5.2 does start with a valid number it returns that.

To prevent this you'd have to test the string you've read for a non-numeric character. The easiest way would be with a regular expression but C doesn't support it, you'd need a library.

I suppose you could read the value in as a float test for non-zero after the decimal. I'm sure there are other methods as well, I'm just drawing a blank on what they may be.


----------



## Dystopia

Cromewell said:


> This is some sample output I get when I run your code:
> 
> The function is doing something or it wouldn't retun any value.



That's what I got. I figured it out though, something was wrong with the way I wrote the code and the way I called the function/wrote the function. Either way, I figured it out.


----------



## Troncoso

Okay, I'm finding that I'll need to validate input for several upcoming projects, so I'm trying to write a function that will check that the number enter is neither a letter, letters, or numbers with decimal values. Heres what I got right now:



		Code:
	

int intCheck(char value[])
{
    int length = strlen(value);
    int num, count;
    
    printf("%d", length);
    
    for (count = 0; count <= length; count++)
    {
        if (value[count] < 0 || value[count] > 9)
        { return 0; }
        else
        { continue; }
    return atoi(value);
    }

int main(int argc, char *argv[])
{
    int count;
    char num[256];
    int total = 1, hold = 0, add;
    printf("Enter a value: ");
    scanf("%c", num);
    
    while (intCheck(num) == 0)
    {
          printf("Invalid input. Please enter a whole number: ");
          scanf("%d", &num);
    }


1. Okay when I run this, I input an int, and it gives me the message "Invalid input. Please enter a whole number: " So I type in another int and it works like it is suppose to. Also, where I have it printing the size of the string, it always prints 3.

2. When I put in something that isn't an int (a decimal or letter) I get an infinite loop of "Invalid input. Please enter a whole number: " 

Thanks again..


----------



## Cromewell

1. Other than using continue and multiple points for return (both you should try to avoid) the functions main problem lies in how you are checking the values. A char is treated as a number or a character depending on the context you are using it in. 'A' = 65, 'B' = 66, etc. When you compare the value to 0 through 9 you are actually looking for a series of nonprintable characters. 0-9 lie in the 48-57 range (ASCII values).

The continue also prevents your return atoi() call from ever happening.

2. Check your scanf calls, they are inconsistant  I'd suggest using %s so that your strings get null terminated.


----------



## Troncoso

Thanks for the advice. I realized after I couldn't get it to work that it was a failing idea. So I scrapped it in favor of this:



		Code:
	

int main()
{
	double number; 
	int count;
	unsigned long total; 
	char input[256];
	
	printf("This program will accept a whole number and return it's factorial.\nPlease enter a whole number: ");
	
	scanf("%lf",&number);
		
	while (number - (1 * trunc(number/1)) != 0)  
	{
		printf("This value is not a whole number. please type a whole number: ");
		
		scanf("%lf", &number);


I just used a double, checked it with the modulus formula and formatted the output at the end. Works perfectly, except I still can't figure out how to check for letters in the input.


----------



## Cromewell

You were on the rught track before, I have a working version of your function from last night. By going back to reading a number you are back to the trap that if characters end up in the input stream it gets stuck trying to read it.



		Code:
	

int intCheck(char value[])
{
    int length = strlen(value);
    int count, num;
    
    //printf("length: %d, value: %s\n", length, value);
    
    for (count = 0; count < length; count++)
    {
        //printf("value[count]: %c, count: %d\n",value[count], count);
        if (value[count] < 48 || value[count] > 57)
        { return 0; }
    }

    num = atoi(value);
    
    return num;
}


----------



## Troncoso

that didnt work for me. can you show me your call statement?


----------



## Cromewell

Sure, it's basically what you already had with a few modifications.


		Code:
	

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int intCheck(char []);

int intCheck(char value[])
{
    int length = strlen(value);
    int count, num;
    
    //printf("length: %d, value: %s\n", length, value);
    
    for (count = 0; count < length; count++)
    {
        //printf("value[count]: %c, count: %d\n",value[count], count);
        if (value[count] < 48 || value[count] > 57)
        { return 0; }
    }

    num = atoi(value);
    
    return num;
}

int main(int argc, char *argv[])
{
    int count;
    char num[256];
    int total = 1, hold = 0, add;
    printf("Enter a value: ");
    scanf("%s", &num);
    
    while (intCheck(num) == 0)
    {
          printf("Invalid input. Please enter a whole number: ");
          scanf("%s", &num);
    }
    
    system("pause");
}


----------



## Troncoso

Dude. Thanks so much for your help. I'm still comparing our 2 functions to find what exactly you did differently, but after some of my own tweaks, it works perfectly. Now that's one thing I don't have to worry about for my next several projects. thanks again.


----------



## Troncoso

What compiler/OS are you using? I've got the function on a separate file but in dev-c++ I just can't get them to compile and link. Though in Ubuntu, gcc does it just fine.


----------



## G3N1US!

speaking of C++ in general, does anyone have problems with Visual Studio 2010? For some reason, mine crashes whenever i debug...So  i just go back to using Dev-C++, but i would prefer using VS if it didn't crash so often.


----------



## G3N1US!

this is the current mini-project i'm making, but i can't seem to figure out how to get one of the buttons to open google chrome or any program.

code:


		Code:
	

#include <windows.h>



/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "WindowsApp";


int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default color as the background of the window */
   wincl.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); 

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "Create a Button",       /* Title Text */
           WS_SYSMENU, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nFunsterStil);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
        
        case WM_CREATE:
             
             CreateWindow(TEXT("button"), TEXT("Click to Continue...."), 
                WS_VISIBLE | WS_CHILD, 
                100,100,300,50,
                hwnd, (HMENU) 1, NULL, NULL
             );
             CreateWindow(TEXT("button"), TEXT("Click to Stop...."),
                WS_VISIBLE | WS_CHILD,
                100,150,300,50,
                hwnd, (HMENU) 3, NULL, NULL
             );
             CreateWindow(TEXT("button"), TEXT("Click To Open Google Chrome"),
                WS_VISIBLE | WS_CHILD,
                100,50,300,50,
                hwnd, (HMENU) 2, NULL, NULL
             );
             
        break;
        
        case WM_COMMAND:
             
             if (LOWORD(wParam) == 1){
                MessageBox(hwnd, "Test Two", "Program1", MB_OK | MB_ICONINFORMATION);
             }
             if (LOWORD(wParam) ==2) {
                MessageBox(hwnd, "Test One" , "Program1", MB_OK | MB_ICONINFORMATION);
             }               
             if (LOWORD(wParam) ==3) {        
                MessageBox(hwnd, "Test Three", "Program1", MB_OK | MB_ICONINFORMATION);                         
             }

        break;
        
        case WM_DESTROY:
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            break;
        default:                      /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}


----------



## Cromewell

I'm using dev c++ on windows. To get them to link you tend to have to include the cpp/h file with your seperate code in it.

I haven't used VS2010, can't help you there.

G3n1us!, I can't get your code to build. I'm assuming you're using VS for it?


----------



## G3N1US!

no, i used Dev-C++ for me, it compiled and ran perfectly


----------



## Cromewell

Strange, my linker is erroring out on this line: wincl.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
saying undefined reference to [email protected] The really strange thing is the type ahead recognizes the function and tells me what parameters it expects.

I've changed it to wincl.hbrBackground = (HBRUSH) (COLOR_BACKGROUND); to make it build.

I think the code you want to use to launch a program is CreateProcess (http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx)


----------



## Troncoso

I included a separate header file but it still wouldn't compile. Then again, I'm using the newest beta version of dev so that may be way there are problems.

G3n1US, I recommend going with visual studio 2008. Have had no provlems with it and you can get the full version free at dreamspark if you are a student


----------



## Cromewell

Troncoso said:


> I included a separate header file but it still wouldn't compile. Then again, I'm using the newest beta version of dev so that may be way there are problems.
> 
> G3n1US, I recommend going with visual studio 2008. Have had no provlems with it and you can get the full version free at dreamspark if you are a student



I'm using 4.9.9.2, I think that's the newest version as well.

You can also get Visual xxx Express Edition from MSDN for free as long as it's not for building commercial software.


----------



## Mark4_4

does anyone know any good C coding books?


----------



## Cromewell

I used C Primer Plus, it was pretty good.


----------



## G3N1US!

@Troncoso 
I cant seem to find VS 2008 though, i looked everywhere.
I do however, have VS 2010 Express, and like i said before, it keeps crashing whenever i compile/debug


----------



## Troncoso

https://www.dreamspark.com/default.aspx

go to download software and you'll find it there. If you are a college student you can download it free.

edit: also allow private messaging.


----------



## G3N1US!

Instant bookmark. Thanks for the link, Troncoso.


----------



## mihir

Finally we have this thread.NICE 


Thanks Cromwell.


I am an engineering student and in the first semester we were taught ANSI C and C++.
Anyways I use Python for Object Oriented Programming.

We used the gcc compiler in any GNU/Linux OS.
The gcc is a really advanced compiler if anyone has ubuntu installed they can try it for themselves you actually get a proper feel of coding if you use the VI or VIM text editor in linux.


Anyways no use of iostream in gcc since all the functions of iostream and fstream are automatically included in that.

And for C++ graphics purposes the only comiler you can use is the turbo C++.
which is a really backward and sucky compiler.
but still graphics.h
is fun to explore if anyone wants i can tell a few functions and programs on it.


PS as for the books.

I would recomend the kernighan and ritchie c book its the best book ever and also written by the creators of c language.







and for data structures I would go with the

Horowitz and Sahani The Fundamentals of Data Structures


----------



## Troncoso

^^^I very much enjoy coding in ubuntu, though I use gedit to write my code. It feels apropriate and it compiles faster as well.


----------



## mihir

Troncoso said:


> ^^^I very much enjoy coding in ubuntu, though I use gedit to write my code. It feels apropriate and it compiles faster as well.



It doesnt matter what text editor you use the code will compile at the same speed.Because gedit is just a text editor and even vim is just a text editor(a more advanced one but still).

Try vim. You wont be able to fully exploit its power without a tutorial but once you get used to it everyother text editor will be useless and obsolete for you.



> sudo apt-get install vim



Even shell programming is fun.

I have a few really good programming problems from my class if you want i can give them to you or post it on this thread and we can discuss the alternative solutions.


----------



## Troncoso

programming problems like simply "make a program that does this"? That'd be cool. I'm actually doing that now. with a couple problems. I've got a factorial generator, a fibonacci series generator, a simple calulator, which I have a question about:

It technically works write, but because of the null terminator that writes to the scanf90 buffer, I always get a minor undesired result. Is there a way to clear the buffer before continuing with the program?


and also, yeah I need tutorials. I tried vi and I can't stand it at the moment.


----------



## mihir

Here are the VIM tutorials

http://www.vi-improved.org/tutorial.php
http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html

As for the code cant help you till you post it.


For me to post problem you need to tell me what have you been taught.
Have you covered pointers,sorting algorithms,search algorithms,linked lists,arrays,multidimensional arrays,stacks queues ,file handling etc etc what all have you covered


----------



## Troncoso

well my question is about the general use of the functions scanf(), sscanf(), etc. I just want to know how to remove the null terminator from the character stream after using the function. I've googled it a lot and found either long functions for what should be something simple, and I've found fflush(stdin)....which didn't work for me. 

The reason I can't give you a code is because this is a problem in any code that I gather user input and then use it in a loop statement. Is that a better explanation?


----------



## Cromewell

> And for C++ graphics purposes the only comiler you can use is the turbo C++.
> which is a really backward and sucky compiler.


That's not strictly true, you can write OpenGL or DirectX Graphics stuff in any compiler, you just need the right header files.


> well my question is about the general use of the functions scanf(), sscanf(), etc. I just want to know how to remove the null terminator from the character stream after using the function. I've googled it a lot and found either long functions for what should be something simple, and I've found fflush(stdin)....which didn't work for me.


fflush is mainly for writing not reading, hence why it doesn't work  What exactly it does on an input stream is library dependant. Clearing the input buffer is non-standard behaviour.

The null terminator is something that you get when you use %s, %c will not add the null terminator. It should be trival to work around though, is there some reason you don't want it?


----------



## mihir

Cromewell said:


> That's not strictly true, you can write OpenGL or DirectX Graphics stuff in any compiler, you just need the right header files.


I have used graphics header file even with a gcc compiler but its a long and painful  procedure.TC comes built in with it and you just have o adjust the linker settings.In many other compilers you need to put the proper header files but in TC it is already their.If you have proper header files you can use it with any compiler you would just need to set the linker and also copy the appropriate files to appropriate folder


----------



## Troncoso

Cromewell said:


> That's not strictly true, you can write OpenGL or DirectX Graphics stuff in any compiler, you just need the right header files.
> 
> fflush is mainly for writing not reading, hence why it doesn't work  What exactly it does on an input stream is library dependant. Clearing the input buffer is non-standard behaviour.
> 
> The null terminator is something that you get when you use %s, %c will not add the null terminator. It should be trival to work around though, is there some reason you don't want it?




I don't have access to my code in question but this is the psuedo code:



		Code:
	

num1 = *function that uses scanf()*
num2 = *that function again()*

printf("Enter an operation: ");
scanf("%c", input);

while input != aCertainValue
{ printf("error message!!!");
   scanf("%c", input);}


The result is this:

Enter a number: error message!!! _

It prints the prompt but immediately jumps to the loop, putting the null terminator in for input and reads it as invalid and displays the error message. Unless something else is going on.


----------



## Cromewell

There must be something else going on, here's the scanf reference page: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

Without being able to step through the code and look at the values as it's running it's hard to say what's going on.


----------



## Troncoso

alright. I'll be able to post my code when I get home. Thanks for the help so far.


----------



## mihir

Problem
It is desirable to have integers that are unlimited in length. But many programming languages have a limited size integer. C language also has the same limitation. The 'int' type has a size of 4 or 8 bytes nowadays. A 4 byte int can store maximum upto 2^32 that is 4294967296. To store higher values, we can create our own datatype called MyInteger.

Suppose we have to store the number 8589934592 (that is 2^33). Then we can store this number by cutting it in multiple parts. For example one way of storing it will be as follows: We store '8' as one digit, '5' as another in 'int's. Then we link up all these ints using a linked list. So in this case, our data type will be

typedef struct node {
 int digit;// can be char digit also, but will be more tricky
 struct node *next;
}node;
Now using this a list can be created, which can be accessed from the first node. So we can define
typedef struct node *MyInteger;

On this structure we can also define functinos like
MyInteger add(MyInteger p, MyInteger q);
void Read(Myinteger *a);
void print(MyInteger a);

Which can be called by the user as:
main() {
 MyInteger a, b, c;
 ......
 read(&a);
 read(&b);
 c = add(a, b);
 print(a);
}


Here a and b are two variables of MyInteger type and they represent two unlimited size integers to the user. The user treats the c = add(a, b) as c = a + b where c, a, b are unlimited size. While implementing the functions, we basically do some linked list manipulation.


one can do the 'split' more carefully for performance. the number 8589934592 can also be split 2 parts only because an 'int' can store upto 2^32 (or 2^31) data. the logic of 'add()' and other functions will also change accordingly. hint: any number can be represented using any base. for example: 123 = 1*10^2 + 2 * 10^1 + 3 * 10^0 spo 123 was represented using base 10. 123 = 1111011 = 1*2^7 + 1*2^6 + 1*2^5 + 1*2^4+ 1 *2^3 + 1 * 2^1 + 1 * 2^0

Assignment
implement an efficient MyInteger type. the type should have following functions:

Myinteger add(Myinteger p, Myinteger q); // adds p and q and returns the addition (as a new list)
Myinteger mult(Myinteger p, Myinteger q); //multiplies integer p and q and returns the result as a new myinteger
Myinteger readmyint();// reads an unlimited size integer from keyboard and returns it.
void print(Myinteger a); // prints a myinteger
Myinteger readfromfile(char *filename); // reads the integer string stored in a file, given as filename, and returns the myinteger created.

for this submit a myinteger.h and myinteger.c files.
write some big integer data in two files (call them one.int and two.int)

write a user program that can be called as follows: (filename: useint.c)
./useint one.int two.int

the program will call the MyInteger functions, add them and print the result of addition and multiplication as a third MyInteger. While printing just print the number, don't print additional stuff like "Myinteger:123412541223".


----------



## Cromewell

Troncoso said:


> alright. I'll be able to post my code when I get home. Thanks for the help so far.


That will help a lot. The pseudo code looks like you're doing everything right, which is why I need to see the actual code.


mihir said:


> Problem
> It is desirable to have integers that are unlimited in length. But many programming languages have a limited size integer. C language also has the same limitation. The 'int' type has a size of 4 or 8 bytes nowadays. A 4 byte int can store maximum upto 2^32 that is 4294967296. To store higher values, we can create our own datatype called MyInteger.
> 
> Suppose we have to store the number 8589934592 (that is 2^33). Then we can store this number by cutting it in multiple parts. For example one way of storing it will be as follows: We store '8' as one digit, '5' as another in 'int's. Then we link up all these ints using a linked list. So in this case, our data type will be
> 
> typedef struct node {
> int digit;// can be char digit also, but will be more tricky
> struct node *next;
> }node;
> Now using this a list can be created, which can be accessed from the first node. So we can define
> typedef struct node *MyInteger;
> 
> On this structure we can also define functinos like
> MyInteger add(MyInteger p, MyInteger q);
> void Read(Myinteger *a);
> void print(MyInteger a);
> 
> Which can be called by the user as:
> main() {
> MyInteger a, b, c;
> ......
> read(&a);
> read(&b);
> c = add(a, b);
> print(a);
> }
> 
> 
> Here a and b are two variables of MyInteger type and they represent two unlimited size integers to the user. The user treats the c = add(a, b) as c = a + b where c, a, b are unlimited size. While implementing the functions, we basically do some linked list manipulation.
> 
> 
> one can do the 'split' more carefully for performance. the number 8589934592 can also be split 2 parts only because an 'int' can store upto 2^32 (or 2^31) data. the logic of 'add()' and other functions will also change accordingly. hint: any number can be represented using any base. for example: 123 = 1*10^2 + 2 * 10^1 + 3 * 10^0 spo 123 was represented using base 10. 123 = 1111011 = 1*2^7 + 1*2^6 + 1*2^5 + 1*2^4+ 1 *2^3 + 1 * 2^1 + 1 * 2^0
> 
> Assignment
> implement an efficient MyInteger type. the type should have following functions:
> 
> Myinteger add(Myinteger p, Myinteger q); // adds p and q and returns the addition (as a new list)
> Myinteger mult(Myinteger p, Myinteger q); //multiplies integer p and q and returns the result as a new myinteger
> Myinteger readmyint();// reads an unlimited size integer from keyboard and returns it.
> void print(Myinteger a); // prints a myinteger
> Myinteger readfromfile(char *filename); // reads the integer string stored in a file, given as filename, and returns the myinteger created.
> 
> for this submit a myinteger.h and myinteger.c files.
> write some big integer data in two files (call them one.int and two.int)
> 
> write a user program that can be called as follows: (filename: useint.c)
> ./useint one.int two.int
> 
> the program will call the MyInteger functions, add them and print the result of addition and multiplication as a third MyInteger. While printing just print the number, don't print additional stuff like "Myinteger:123412541223".


Is this the solution that you were asked to create for this assignment? Doing math on compound fields like that can be tricky. Luckily, addition and multiplication aren't so bad, I did something similar by using a string to store the number instead of chained integers.


----------



## mihir

Cromewell said:


> That will help a lot. The pseudo code looks like you're doing everything right, which is why I need to see the actual code.
> 
> Is this the solution that you were asked to create for this assignment? Doing math on compound fields like that can be tricky. Luckily, addition and multiplication aren't so bad, I did something similar by using a string to store the number instead of chained integers.



I have already done this and got a 10 on 10 in class.This question is for other to try.
Post me your solutions.I will also post mine later when  everyone has tried


----------



## Troncoso

Haha, besides the 3 of us (rather the 2 of you) no one on the forums has expressed enough interest in C to actually post about it. Makes me sad. I'd love to compare and learn from others who are learning the language. As for the problem, while I understand it for the most part, it's still a bit over my head, so I have to pass.


----------



## Troncoso

Okay this is dumb. I'm having all sorts of trouble with char arrays:

I am making a simple function that takes a string and reverses the characters.

here is the function call:


		Code:
	

char string[256], reverse[256];
printf("This program takes a string and reverses it. So let's go!\n");
printf("Please type a word or phrase: ");
scanf("%s", string);
    
reverse = reverseString(string);


and here is the function (doesn't reverse yet):



		Code:
	

char* reverseString(char[]);

char* reverseString(input[])
{
     char reversed[256];
     int length = strlen(input);
     
     reversed = "yes";
     return reversed;
}


This gives me all kinds of errors involving the prototype declaration, the use of input, and whatnot. So, how do you properly:

pass to a function
define a function
return from a function

using char arrays???


----------



## Cromewell

Your mistake is in the function declaration, you are missing the datatype, but there are other problems. You are also getting into pointers here which can be confusing. I need to build a few versions to try and remeber all this, it's been a while for me.


----------



## Troncoso

actually I just noticed this stupid mistake:



		Code:
	

reversed = "yes";


haha. I know you can't do that.

EDIT: pointers annoy the hell out of me. I just can't understand their usefulness and without that, I can't understand how to use them. Like in my situation, I have no idea how to properly set up a pointer to allow what I'm doing


----------



## Cromewell

So one important thing to understand is the way C/C++ treats arrays when you pass them to a function.

With your function: char* reverseString(char input[])
input is actually a pointer to the array you've passed. This means if you do anything to it in the function that change also exists in the 'outside world' so to speak.

Take this trivial example:


		Code:
	

void example(int[]);

void example(int arr[]){
  arr[0] = 5;
}

int main(){
 int array[5] = {1,2,3,4,5};
 //array contains 1,2,3,4,5
 example(array);
 //array now contains 5,2,3,4,5
}


There are easy 2 ways I think you can work your reversing function. 1 is to reverse the string in place the second is to take the return value as a second parameter like:


		Code:
	

void reverseString(char input[], char reversed[])
{
//put your logic here
}


----------



## Mark4_4

try using strrev()


----------



## brian

Ok so I need to figure out what to use. I want to make an uno isk game such that you will be given a random set of cards with two numbers attached to it, Ie a number from 1-10 (face value) and a number 1-4 (color) I was thinking an array such that each two sets of data would be one card ie x[] = {7,3,6,4} however I want to be able to delete any two values and have them move the whole array down ie from the old example delete the 7,3 card and have the array = {6,4}. Because of that I looked into lists but it also seems a bit too complex for this idea. Any ideas on what I can use. I also want to be able to call the numbers quickly.


----------



## Cromewell

strrev isn't a standard function I think that is a Visual C++ bonus function, there is a reverse function but it's a C++ template and works on vectors.

Brian: a 2 dimensional array may work for you if you don't want to use objects.


----------



## brian

Cromewell said:


> strrev isn't a standard function I think that is a Visual C++ bonus function, there is a reverse function but it's a C++ template and works on vectors.
> 
> Brian: a 2 dimensional array may work for you if you don't want to use objects.



How can I delete a value and move the rest down one to fill it in?


----------



## Cromewell

If you actually want to resize the array you are looking at malloc calls. From that point of view a linked list is easier but you'll want to watch out for memory leaks.

I suppose you could probably use a place holder array to simplify it and only use a pointer to the start of your array.


----------



## Mark4_4

Cromewell said:


> strrev isn't a standard function I think that is a Visual C++ bonus function, there is a reverse function but it's a C++ template and works on vectors.
> 
> Brian: a 2 dimensional array may work for you if you don't want to use objects.



My bad i started using c++ before i moved onto C


----------



## brian

Ok so I have something up with this,

I have a random number generator that looks like this 


		Code:
	

int random(int min, int max) {
	srand(time(NULL));
	double r = ((((rand()% 100)/99)*(max - 1)) + min);
	r = floor(r);
	return r;
}

 however its not generating a random number, the only two numbers I got were 1 and 4. What am I doing wrong.


----------



## Cromewell

I think your error is in the part where you calculte the random number bounds. I used double r = rand() * 10000000 % (max - min) + min; and it seems to make a random number.


----------



## AE7

brian said:


> Ok so I have something up with this,
> 
> I have a random number generator that looks like this
> 
> 
> Code:
> 
> 
> int random(int min, int max) {
> srand(time(NULL));
> double r = ((((rand()% 100)/99)*(max - 1)) + min);
> r = floor(r);
> return r;
> }
> 
> however its not generating a random number, the only two numbers I got were 1 and 4. What am I doing wrong.



Put that call to srand() in your main function - srand() must only be called once and with it being in this random() function, srand() is called every time random() is called.


----------



## Dystopia

Troncoso said:


> Haha, besides the 3 of us (rather the 2 of you) no one on the forums has expressed enough interest in C to actually post about it. Makes me sad. I'd love to compare and learn from others who are learning the language. As for the problem, while I understand it for the most part, it's still a bit over my head, so I have to pass.



I really like writing in C++. The other day I wrote and rewrote a program for 6 hours, just to have a classmate point out I didn't have the line using namespace std; in a function, which fixed the program. I was rather happy. 

I generally read posts rather than post because everyone here is at a much higher level, so when someone posts code, asking for help, well,  I just barely understand the code, sometimes not at all


----------



## kobaj

I've got a fun question if someone would like to help. 

In my C++ class we were required to make a card game. As such, I had three classes. A card class, which had two enums for Suit and Cardinal. A deck class, with a private vector<card> *mycarddeck = new vector<card>(52) And a main class called game which had its own Deck mydeck(). The other details shouldn't matter at this moment.

Now, if within the game I needed to access something like mydeck.mycarddeck->at(). I couldn't. Simply because mycarddeck is private. So I created an accessor method, within Deck called at() which returned mycarddeck->at(). IE, allowing me to simply mydeck.at().

HOWEVER, my professor said this was TERRIBLE. "You wasted a lot of time" blah blah. And when I asked "how else would you recommend I gain access to at() then since it is private?" he basically replied "figure it out".

So I am here. 

Is there something in C++ that I'm missing? Magical ability to override private declaration without using inheritance? Perhaps not using vector methods outside of Deck in the first place?


----------



## AE7

kobaj said:


> I've got a fun question if someone would like to help.
> 
> In my C++ class we were required to make a card game. As such, I had three classes. A card class, which had two enums for Suit and Cardinal. A deck class, with a private vector<card> *mycarddeck = new vector<card>(52) And a main class called game which had its own Deck mydeck(). The other details shouldn't matter at this moment.
> 
> Now, if within the game I needed to access something like mydeck.mycarddeck->at(). I couldn't. Simply because mycarddeck is private. So I created an accessor method, within Deck called at() which returned mycarddeck->at(). IE, allowing me to simply mydeck.at().
> 
> HOWEVER, my professor said this was TERRIBLE. "You wasted a lot of time" blah blah. And when I asked "how else would you recommend I gain access to at() then since it is private?" he basically replied "figure it out".
> 
> So I am here.
> 
> Is there something in C++ that I'm missing? Magical ability to override private declaration without using inheritance? Perhaps not using vector methods outside of Deck in the first place?



All of my profs recommend accessor methods for purposes like yours. But there are some profs who just don't think logically and practically, been there, done that.

It would make little sense, but would this prof want you to make a Deck object, then derive objects like PlayerDeck or GameDeck from that?


----------



## mihir

kobaj said:


> I've got a fun question if someone would like to help.
> 
> In my C++ class we were required to make a card game. As such, I had three classes. A card class, which had two enums for Suit and Cardinal. A deck class, with a private vector<card> *mycarddeck = new vector<card>(52) And a main class called game which had its own Deck mydeck(). The other details shouldn't matter at this moment.
> 
> Now, if within the game I needed to access something like mydeck.mycarddeck->at(). I couldn't. Simply because mycarddeck is private. So I created an accessor method, within Deck called at() which returned mycarddeck->at(). IE, allowing me to simply mydeck.at().
> 
> HOWEVER, my professor said this was TERRIBLE. "You wasted a lot of time" blah blah. And when I asked "how else would you recommend I gain access to at() then since it is private?" he basically replied "figure it out".
> 
> So I am here.
> 
> Is there something in C++ that I'm missing? Magical ability to override private declaration without using inheritance? Perhaps not using vector methods outside of Deck in the first place?



there are two ways to access a private inline function.
either you make a function in the public visibility mode and call the private function and then call the public function or you can also make a friend function which has access to all the private member variables and functions.




As for Troncoso's Problem


try this.
Make a doubly circular linked list and use this as an input for your string and then reverse the linked list.You can either do this by pointers or by just exchanging the data in the nodes or you can just output the reverse whatever you want and that way your string will also be dynamically allocated and unlimited


----------



## AE7

mihir said:


> there are two ways to access a private inline function.
> either you make a function in the public visibility mode and call the private function and then call the public function or you can also make a friend function which has access to all the private member variables and functions.
> 
> 
> 
> 
> As for Troncoso's Problem
> 
> 
> try this.
> Make a doubly circular linked list and use this as an input for your string and then reverse the linked list.You can either do this by pointers or by just exchanging the data in the nodes or you can just output the reverse whatever you want and that way your string will also be dynamically allocated and unlimited



Friend functions would do the trick.

Troncoso could also use the STL's Deque


----------



## brian

AE7 said:


> Put that call to srand() in your main function - srand() must only be called once and with it being in this random() function, srand() is called every time random() is called.



Thanks!

Well if anyone wants a fun game...


		Code:
	

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <cstdlib>
#include <stdio.h>
#include <vector>
using namespace std;

int random(int, int);
int player();
int computer();
int pcard[2][100]; //players card deck
int ccard[2][100]; //computers card deck
int pnumber = 0; // number of cards (in c++ form ie 0 = 1) player has
int cnumber = 0; // " " "
int lastcard[2][1];//the last card played
int rnumseed = 10; //random number seed itteration count
void main ()
{
	srand(time(NULL));
	//Give players 5 random cards
	for (int i = 0; i< 5; ++i) {
			pcard[0][i] = random(1,10);
			pcard[1][i] = random(1,4);
			pnumber++;
			ccard[0][i] = random(1,10);
			ccard[1][i] = random(1,4);
			cnumber++;
	}
	--pnumber;
	--cnumber;
	//create random card to start
	lastcard[0][0] = random(1,10);
	lastcard[1][0] = random(1,4);
	//plays until all cards are gone
	do {
		player();
		computer();
		if (cnumber == 0)
			cout << "\n\nUNO!" << endl;
	}while (cnumber >= 0 && pnumber >= 0);
	if (cnumber < 0)
		cout << "\nThe computer wins :(" << endl;
	else
		cout <<"\nYou win!!! :)" << endl;

}

int random(int min, int max) {
	//seed for random number, have it incress each time, very random mostly.
	double r = (((((rand()*rnumseed)% 100)/99.)*(max)) + min);
	//cout << r <<endl;
	r = floor(r);
	if (r > max) {
		r=max;
	}
	rnumseed +=17;
	return r;
}

int player() {
	cout << endl;
	start: //used if card is incorrect
	int tempdeck[2][100]; //temp deck to remove the card played
	int cardchoice; // the input of what card to use
	cout << "Player it is your turn, the current card is\n" << lastcard[0][0] << "," << lastcard[1][0] <<endl; 
	cout << "Your current cards are" <<endl;
	for (int i = pnumber; i >= 0; --i) { //loops to display the cards in their hand. 
		cout << "(" << i+1 << ")"<< pcard[0][i] << "," << pcard [1][i] << " ";
	}
	/*cout << "The computers cards are:" <<endl;
	//for (int i = cnumber; i >= 0; --i) { //loops to display the cards in their hand.   //debug
	//	cout << "(" << i+1 << ")"<< ccard[0][i] << "," << ccard [1][i] << " ";
	}*/
	cout <<"\nEnter the card to use, or 0 to draw" <<endl;
	cin >> cardchoice;
	if (cardchoice == 0) { //draws a new card and adds it to the last number, also incresses the number of cards. This is if the user chooses 0
		pnumber++;
		pcard[0][pnumber] = random(1,10);
		pcard[1][pnumber] = random(1,4);
		cout <<"You recieved " << pcard[0][pnumber] << "," << pcard[1][pnumber] <<endl;
	}
	else{
		--cardchoice; //puts the card the user choose into c++ terms
		if (pcard[0][cardchoice] == lastcard[0][0] || pcard[1][cardchoice] == lastcard[1][0]) //checks to make sure the card will work
		{
			lastcard[0][0] = pcard[0][cardchoice];//updayes the latest card on the desk
			lastcard[1][0] = pcard[1][cardchoice];
			for (int i = pnumber; i >=0; --i) { //removes the last card used from the players deck
				if (i > cardchoice) {
					tempdeck[0][i-1] = pcard[0][i]; 
					tempdeck[1][i-1] = pcard[1][i];
				}
				else if (i == cardchoice)
				{
				}
				else if (i < cardchoice)
				{
					tempdeck[0][i] = pcard[0][i];
					tempdeck[1][i] = pcard[1][i];
				}
			}
			--pnumber; //decresses number of cards the user has
			pcard[0][pnumber+1] = 0;
			pcard[1][pnumber+1] = 0;
			for (int i = pnumber; i >= 0; --i) { //moves the temp deck to the real deck
				pcard[0][i] = tempdeck[0][i];
				pcard[1][i] = tempdeck[1][i];
			}
		}
		else { //if the card does not work
			cout << "You entered an invalad card try again" << endl;
			goto start;
		}
	}
	return(0);
}
int computer() {
	bool placed = 0;
	cout << "Its the computers turn" << endl;
	int tempdeck[2][100];
	for (int i = cnumber; i >= 0; --i) {
		int cardchoice = i;
		if (ccard[0][i] == lastcard[0][0] || ccard[1][i] == lastcard[1][0]) {
			lastcard[0][0] = ccard[0][i];
			lastcard[1][0] = ccard[1][i];
			for (int x = cnumber; x >=0; --x) { //removes the last card used from the players deck
				if (x > cardchoice) {
					tempdeck[0][x-1] = ccard[0][x]; 
					tempdeck[1][x-1] = ccard[1][x];
				}
				else if (x == cardchoice)
				{
				}
				else if (x < cardchoice)
				{
					tempdeck[0][x] = ccard[0][x];
					tempdeck[1][x] = ccard[1][x];
				}
			}
			--cnumber;
			ccard[0][cnumber+1] = 0;
			ccard[1][cnumber+1] = 0;
			for (int x = cnumber; x >= 0; --x) { //moves the temp deck to the real deck
				ccard[0][x] = tempdeck[0][x];
				ccard[1][x] = tempdeck[1][x];
			}
			cout << "The computer used " << lastcard[0][0] << "," << lastcard[1][0] <<endl;
			placed =1;
			break;
		}
	}
	if (placed == 0){
		++cnumber;
		ccard[0][cnumber] = random(1,10);
		ccard[1][cnumber] = random(1,4);
		cout << "The computer drew a card" << endl;
	}
	return(0);
}

Sorry I don't like to remove my header files


----------



## mihir

AE7 said:


> Friend functions would do the trick.
> 
> *Troncoso could also use the STL's Deque*



I always like to use Double Linked List since almost same coding required but way easier further manipulation.



AE7 said:


> *Friend functions would do the trick.
> 
> *Troncoso could also use the STL's Deque


So would a public function calling the private function


----------



## mihir

Declare a structure with a self referential variable and then give some function declaration which you will use.
Then save it as a header file.
Then Write a .c file and define all the function you declared in the header file and include the header file in this file.Then make another .c and declare the main function and and call the approprite functions.And you have an unlimited string.and also anyother task you want to do with that code.
compile your program like this

gcc declaration.c main.c


----------



## Cromewell

AE7 said:


> Put that call to srand() in your main function - srand() must only be called once and with it being in this random() function, srand() is called every time random() is called.


You can seed the random all you want, it doesn't really matter if you are seeding with time(null).


kobaj said:


> I've got a fun question if someone would like to help.
> 
> In my C++ class we were required to make a card game. As such, I had three classes. A card class, which had two enums for Suit and Cardinal. A deck class, with a private vector<card> *mycarddeck = new vector<card>(52) And a main class called game which had its own Deck mydeck(). The other details shouldn't matter at this moment.
> 
> Now, if within the game I needed to access something like mydeck.mycarddeck->at(). I couldn't. Simply because mycarddeck is private. So I created an accessor method, within Deck called at() which returned mycarddeck->at(). IE, allowing me to simply mydeck.at().
> 
> HOWEVER, my professor said this was TERRIBLE. "You wasted a lot of time" blah blah. And when I asked "how else would you recommend I gain access to at() then since it is private?" he basically replied "figure it out".
> 
> So I am here.
> 
> Is there something in C++ that I'm missing? Magical ability to override private declaration without using inheritance? Perhaps not using vector methods outside of Deck in the first place?


One method would be to have a function that returns the deck vector instead of a card at a position. It's hard to say what exactly they are looking for, I always had to make a rediculous amount of accessor methods in school.


----------



## Dystopia

brian said:


> Thanks!
> 
> Well if anyone wants a fun game...
> 
> 
> Code:
> 
> 
> #include <iostream>
> #include <iomanip>
> #include <string>
> #include <cmath>
> #include <cstdlib>
> #include <stdio.h>
> #include <vector>
> using namespace std;
> 
> int random(int, int);
> int player();
> int computer();
> int pcard[2][100]; //players card deck
> int ccard[2][100]; //computers card deck
> int pnumber = 0; // number of cards (in c++ form ie 0 = 1) player has
> int cnumber = 0; // " " "
> int lastcard[2][1];//the last card played
> int rnumseed = 10; //random number seed itteration count
> void main ()
> {
> srand(time(NULL));
> //Give players 5 random cards
> for (int i = 0; i< 5; ++i) {
> pcard[0][i] = random(1,10);
> pcard[1][i] = random(1,4);
> pnumber++;
> ccard[0][i] = random(1,10);
> ccard[1][i] = random(1,4);
> cnumber++;
> }
> --pnumber;
> --cnumber;
> //create random card to start
> lastcard[0][0] = random(1,10);
> lastcard[1][0] = random(1,4);
> //plays until all cards are gone
> do {
> player();
> computer();
> if (cnumber == 0)
> cout << "\n\nUNO!" << endl;
> }while (cnumber >= 0 && pnumber >= 0);
> if (cnumber < 0)
> cout << "\nThe computer wins :(" << endl;
> else
> cout <<"\nYou win!!! :)" << endl;
> 
> }
> 
> int random(int min, int max) {
> //seed for random number, have it incress each time, very random mostly.
> double r = (((((rand()*rnumseed)% 100)/99.)*(max)) + min);
> //cout << r <<endl;
> r = floor(r);
> if (r > max) {
> r=max;
> }
> rnumseed +=17;
> return r;
> }
> 
> int player() {
> cout << endl;
> start: //used if card is incorrect
> int tempdeck[2][100]; //temp deck to remove the card played
> int cardchoice; // the input of what card to use
> cout << "Player it is your turn, the current card is\n" << lastcard[0][0] << "," << lastcard[1][0] <<endl;
> cout << "Your current cards are" <<endl;
> for (int i = pnumber; i >= 0; --i) { //loops to display the cards in their hand.
> cout << "(" << i+1 << ")"<< pcard[0][i] << "," << pcard [1][i] << " ";
> }
> /*cout << "The computers cards are:" <<endl;
> //for (int i = cnumber; i >= 0; --i) { //loops to display the cards in their hand.   //debug
> //	cout << "(" << i+1 << ")"<< ccard[0][i] << "," << ccard [1][i] << " ";
> }*/
> cout <<"\nEnter the card to use, or 0 to draw" <<endl;
> cin >> cardchoice;
> if (cardchoice == 0) { //draws a new card and adds it to the last number, also incresses the number of cards. This is if the user chooses 0
> pnumber++;
> pcard[0][pnumber] = random(1,10);
> pcard[1][pnumber] = random(1,4);
> cout <<"You recieved " << pcard[0][pnumber] << "," << pcard[1][pnumber] <<endl;
> }
> else{
> --cardchoice; //puts the card the user choose into c++ terms
> if (pcard[0][cardchoice] == lastcard[0][0] || pcard[1][cardchoice] == lastcard[1][0]) //checks to make sure the card will work
> {
> lastcard[0][0] = pcard[0][cardchoice];//updayes the latest card on the desk
> lastcard[1][0] = pcard[1][cardchoice];
> for (int i = pnumber; i >=0; --i) { //removes the last card used from the players deck
> if (i > cardchoice) {
> tempdeck[0][i-1] = pcard[0][i];
> tempdeck[1][i-1] = pcard[1][i];
> }
> else if (i == cardchoice)
> {
> }
> else if (i < cardchoice)
> {
> tempdeck[0][i] = pcard[0][i];
> tempdeck[1][i] = pcard[1][i];
> }
> }
> --pnumber; //decresses number of cards the user has
> pcard[0][pnumber+1] = 0;
> pcard[1][pnumber+1] = 0;
> for (int i = pnumber; i >= 0; --i) { //moves the temp deck to the real deck
> pcard[0][i] = tempdeck[0][i];
> pcard[1][i] = tempdeck[1][i];
> }
> }
> else { //if the card does not work
> cout << "You entered an invalad card try again" << endl;
> goto start;
> }
> }
> return(0);
> }
> int computer() {
> bool placed = 0;
> cout << "Its the computers turn" << endl;
> int tempdeck[2][100];
> for (int i = cnumber; i >= 0; --i) {
> int cardchoice = i;
> if (ccard[0][i] == lastcard[0][0] || ccard[1][i] == lastcard[1][0]) {
> lastcard[0][0] = ccard[0][i];
> lastcard[1][0] = ccard[1][i];
> for (int x = cnumber; x >=0; --x) { //removes the last card used from the players deck
> if (x > cardchoice) {
> tempdeck[0][x-1] = ccard[0][x];
> tempdeck[1][x-1] = ccard[1][x];
> }
> else if (x == cardchoice)
> {
> }
> else if (x < cardchoice)
> {
> tempdeck[0][x] = ccard[0][x];
> tempdeck[1][x] = ccard[1][x];
> }
> }
> --cnumber;
> ccard[0][cnumber+1] = 0;
> ccard[1][cnumber+1] = 0;
> for (int x = cnumber; x >= 0; --x) { //moves the temp deck to the real deck
> ccard[0][x] = tempdeck[0][x];
> ccard[1][x] = tempdeck[1][x];
> }
> cout << "The computer used " << lastcard[0][0] << "," << lastcard[1][0] <<endl;
> placed =1;
> break;
> }
> }
> if (placed == 0){
> ++cnumber;
> ccard[0][cnumber] = random(1,10);
> ccard[1][cnumber] = random(1,4);
> cout << "The computer drew a card" << endl;
> }
> return(0);
> }
> 
> Sorry I don't like to remove my header files



Turn it into an .exe! I really cbf to move the headers into functions and change the main function for VS.


----------



## mihir

The game above it didnt work for me it went into an infinite loop when i selected a card.


----------



## AE7

Cromewell said:


> You can seed the random all you want, it doesn't really matter if you are seeding with time(null).



While that is true, calling it once is out an idea of best practice.

It does nothing to increase the randomness of the numbers generated by the rand() function-no need to dirty up code by calling srand() multiple times.


----------



## brian

mihir said:


> The game above it didnt work for me it went into an infinite loop when i selected a card.



Thats weird, what compiler are you using? I used VB 2010 and it works without a glitch


----------



## mihir

brian said:


> Thats weird, what compiler are you using? I used VB 2010 and it works without a glitch



I used a Bloodshed Dev C++


----------



## brian

Ok I have  one where I dont know where to start..


> Write a program that reads a key pressed on the keyboard and displays its code on the screen. Use the program to determine the code for the Enter key. Then write a function named ReadOneChar() that reads a character and ignores any succeeding characters until the Enter key is pressed. The entered character should be returned by ReadOneChar().



I need some help to start off. I know of cin but I feel this program is asking for something else (ie. it wants me to figure out the code for the enter key)

Any ideas?


----------



## mihir

Every keyboard button has a carriage return code which is different for every programming language.For C/C++ the carriage return code for the "return" key is the escape code '\n'.Or they might also be talking about non language specific codes like for enter the code will be U+21B.
The first one is easy to make but the second one would need some thinking.You can use the getc function which reads a character and returns and integer and also gives suitable return on end of file.which will be the ascii sequence of the pressed letter.I can write the code for you if you want.But in C


----------



## Cromewell

It's hard to say, they are probably asking you to use the get function. I think this will work as a starting point (should read until a newline character is found)


		Code:
	

char c_input;
bool b_keepReading = true;
while(b_keepReading){
 cin.get(&c_input);
 if (c_input == "\n"){
  b_keepReading = false;
 }
}


----------



## brian

I just used the getch() function, It worked. Since they were so vague, I think it will work. Thanks for the hints.


----------



## mihir

Nice?


I wanted to know have you guys been taught about time complexity and space complexity and stuff in languages


----------



## Dystopia

Ok guys, need some help here. I want to turn in this assignment by the latest Wednesday. 

I need to write a program that reads numbers out of a .dat file, into an array. Then it needs to find the standard devation, range, median, and average. I've got the code for the average done, thats easy. I'd need help with the code on the deviation. And, I need help on sorting the numbers. I cannot figure out how to sort the numbers from lowest to highest (or any way, for that matter). No matter what I try, no dice. I did look in my book, but I can't really do it the way they show it, as they are not taking the numbers in the arrays.

So, to clarify, I need to figure out how to sort the numbers. And still be able to access them of course. Here is the code I have, which does not work. No errors, just a BS number (like -9 trillion or something):



		Code:
	

//sort.cpp sorts the index from lowest value to highest value
//
//Adam Holthaus

#include "stdafx.h"
#include <iostream>
using namespace std;

double sort(double index[], int esave)
{
	//Initializing variable
	int n, min, entry, edefine;


	for(edefine = 0; edefine < esave; edefine++)
	{
		min = index[edefine];
		n = edefine;

		for(entry = edefine; entry < esave; entry++)
		{
			if(index[n] < min)
			{
				min = index[n];
				n = entry;
			}
		}

		index[n] = index[edefine];
		index[edefine] = min;
	}

	return index[esave];
}


esave stands for the amount of numbers in the array. I kept track reading out of an array. index[] is my array, which already has the numbers in it. You can see what I did in the code...what's wrong.

I think it might be easiest if you made your own .dat file or .txt file.

Thanks guys.


----------



## Geoff

Code:
	

<echo>
Hello World!
</echo>


----------



## Cromewell

31!m!n80r said:


> Ok guys, need some help here. I want to turn in this assignment by the latest Wednesday.
> 
> I need to write a program that reads numbers out of a .dat file, into an array. Then it needs to find the standard devation, range, median, and average. I've got the code for the average done, thats easy. I'd need help with the code on the deviation. And, I need help on sorting the numbers. I cannot figure out how to sort the numbers from lowest to highest (or any way, for that matter). No matter what I try, no dice. I did look in my book, but I can't really do it the way they show it, as they are not taking the numbers in the arrays.
> 
> So, to clarify, I need to figure out how to sort the numbers. And still be able to access them of course. Here is the code I have, which does not work. No errors, just a BS number (like -9 trillion or something):
> 
> 
> 
> Code:
> 
> 
> //sort.cpp sorts the index from lowest value to highest value
> //
> //Adam Holthaus
> 
> #include "stdafx.h"
> #include <iostream>
> using namespace std;
> 
> double sort(double index[], int esave)
> {
> //Initializing variable
> int n, min, entry, edefine;
> 
> 
> for(edefine = 0; edefine < esave; edefine++)
> {
> min = index[edefine];
> n = edefine;
> 
> for(entry = edefine; entry < esave; entry++)
> {
> if(index[n] < min)
> {
> min = index[n];
> n = entry;
> }
> }
> 
> index[n] = index[edefine];
> index[edefine] = min;
> }
> 
> return index[esave];
> }
> 
> 
> esave stands for the amount of numbers in the array. I kept track reading out of an array. index[] is my array, which already has the numbers in it. You can see what I did in the code...what's wrong.
> 
> I think it might be easiest if you made your own .dat file or .txt file.
> 
> Thanks guys.


Do you have to write your own sorter function? qsort is built into cstdlib and is quite good at what it does. edit: Here's a simple insertion sort, you can find the algorithm all over the place.


		Code:
	

void sort(double d_array[], int i_arrSize)
{
    int i_swap;
    double d_temp;
    
    for (int x = 0; x < i_arrSize; x++){
        d_temp = d_array[x];
        i_swap = x-1;
        
        while(d_temp < d_array[i_swap] && i_swap >= 0){
            d_array[i_swap+1] = d_array[i_swap];
            i_swap--;
        }
        
        d_array[i_swap+1] = d_temp;
    }
}

/edit
Can you explain this function to me, why are you returning the last element of the array?


			
				[-0MEGA-];1610703 said:
			
		

> Code:
> 
> 
> <echo>
> Hello World!
> </echo>


That's the strangest C++ I have ever seen....


----------



## mihir

31!m!n80r said:


> Ok guys, need some help here. I want to turn in this assignment by the latest Wednesday.
> 
> I need to write a program that reads numbers out of a .dat file, into an array. Then it needs to find the standard devation, range, median, and average. I've got the code for the average done, thats easy. I'd need help with the code on the deviation. And, I need help on sorting the numbers. I cannot figure out how to sort the numbers from lowest to highest (or any way, for that matter). No matter what I try, no dice. I did look in my book, but I can't really do it the way they show it, as they are not taking the numbers in the arrays.
> 
> So, to clarify, I need to figure out how to sort the numbers. And still be able to access them of course. Here is the code I have, which does not work. No errors, just a BS number (like -9 trillion or something):
> 
> 
> 
> Code:
> 
> 
> //sort.cpp sorts the index from lowest value to highest value
> //
> //Adam Holthaus
> 
> #include "stdafx.h"
> #include <iostream>
> using namespace std;
> 
> double sort(double index[], int esave)
> {
> //Initializing variable
> int n, min, entry, edefine;
> 
> 
> for(edefine = 0; edefine < esave; edefine++)
> {
> min = index[edefine];
> n = edefine;
> 
> for(entry = edefine; entry < esave; entry++)
> {
> if(index[n] < min)
> {
> min = index[n];
> n = entry;
> }
> }
> 
> index[n] = index[edefine];
> index[edefine] = min;
> }
> 
> return index[esave];
> }
> 
> 
> esave stands for the amount of numbers in the array. I kept track reading out of an array. index[] is my array, which already has the numbers in it. You can see what I did in the code...what's wrong.
> 
> I think it might be easiest if you made your own .dat file or .txt file.
> 
> Thanks guys.


You cannot return arrays like that.
You can try writing your own quick sort.Since it is the second fastest sorting algorithm(excluding radix sort) and also the most space efficient.
And if space is not a constriction then a merge sort would do.
Have you been given a time complexity or not.If not then even a bubble sort would do.


		Code:
	

<echo>
Hello World!
</echo>

Thats HTML


----------



## Cromewell

mihir said:


> You cannot return arrays like that.
> You can try writing your own quick sort.Since it is the second fastest sorting algorithm(excluding radix sort) and also the most space efficient.
> And if space is not a constriction then a merge sort would do.
> Have you been given a time complexity or not.If not then even a bubble sort would do.



I wouldn't suggest a bubble sort even for the simplest array of data. I'm hoping it's not even taught in schools anymore. A selection sort is way more efficient and not very difficult to implement and the insertion sort (that I posted above) is a little faster still.


----------



## Dystopia

mihir said:


> You cannot return arrays like that.
> You can try writing your own quick sort.Since it is the second fastest sorting algorithm(excluding radix sort) and also the most space efficient.
> And if space is not a constriction then a merge sort would do.
> Have you been given a time complexity or not.If not then even a bubble sort would do.
> 
> 
> Code:
> 
> 
> <echo>
> Hello World!
> </echo>
> 
> Thats HTML


Pointing out the fact that I was returning the array the way I was probably fixed it, let me see. What do you mean with a quick sort? Or merge sort? Time is not an issue, neither is space. From what I saw, the bubble sort doesn't seem like it will work well for this. 


Cromewell said:


> Do you have to write your own sorter function? qsort is built into cstdlib and is quite good at what it does. edit: Here's a simple insertion sort, you can find the algorithm all over the place.
> 
> 
> Code:
> 
> 
> void sort(double d_array[], int i_arrSize)
> {
> int i_swap;
> double d_temp;
> 
> for (int x = 0; x < i_arrSize; x++){
> d_temp = d_array[x];
> i_swap = x-1;
> 
> while(d_temp < d_array[i_swap] && i_swap >= 0){
> d_array[i_swap+1] = d_array[i_swap];
> i_swap--;
> }
> 
> d_array[i_swap+1] = d_temp;
> }
> }
> 
> /edit
> Can you explain this function to me, why are you returning the last element of the array?
> 
> That's the strangest C++ I have ever seen....



Yeah, I have to write my own (but I'm allowed to get help). Why all the underscores in the one you posted? Just confuses me 

I don't know why I am returning the index with the last element...I'm going to fix that, and try it again, thanks.

EDIT: Didn't fix it.

Anyone know what I should be returning?

Also, thanks for the code Cromewell, I'm using it. Will update later.

EDIT2: still not working...


----------



## Cromewell

31!m!n80r said:


> Pointing out the fact that I was returning the array the way I was probably fixed it, let me see. What do you mean with a quick sort? Or merge sort? Time is not an issue, neither is space. From what I saw, the bubble sort doesn't seem like it will work well for this.
> 
> 
> Yeah, I have to write my own (but I'm allowed to get help). Why all the underscores in the one you posted? Just confuses me
> 
> I don't know why I am returning the index with the last element...I'm going to fix that, and try it again, thanks.
> 
> EDIT: Didn't fix it.
> 
> Anyone know what I should be returning?
> 
> Also, thanks for the code Cromewell, I'm using it. Will update later.
> 
> EDIT2: still not working...



You don't need to return anything. The array is passed as a pointer. The underscores are there because I prefix the variable name with the type, it's just a habit. The only place I don't do it is in for loop counters.

Here's the full test framework I was using for it. It's working here.


		Code:
	

//sort.cpp sorts the index from lowest value to highest value
//
//Adam Holthaus

#include <iostream>
#include <cstdlib>
#include <cstdio>

void sort(double, int);

using namespace std;

void sort(double d_array[], int i_arrSize)
{
    int i_swap;
    double d_temp;
    
    for (int x = 0; x < i_arrSize; x++){
        d_temp = d_array[x];
        i_swap = x-1;
        
        while(d_temp < d_array[i_swap] && i_swap >= 0){
            d_array[i_swap+1] = d_array[i_swap];
            i_swap--;
        }
        
        d_array[i_swap+1] = d_temp;
    }
}

int main(){
    double d_sortMe[] = {1.0,2.0,5.0,3.0,6.0,2.5,1.3};
    int i_arrSize = sizeof(d_sortMe)/sizeof(double);

    printf("Original Order\n");
    printf("------------------------\n");    

    for (int x = 0; x < i_arrSize; x++){
        printf("%lf\n",d_sortMe[x]);
    }

    printf("------------------------\n");
    printf("Sorted\n");
    printf("------------------------\n");
            
    sort(d_sortMe, sizeof(d_sortMe)/sizeof(double));
    
    for (int x = 0; x < i_arrSize; x++){
        printf("%lf\n",d_sortMe[x]);
    }

    printf("------------------------\n");
    
    system("pause");
    
    return 0;
}


----------



## Dystopia

Is that in C? Because in for us, in C++, to print something to a screen, we use 



		Code:
	

cout << "whatever you want to say";


----------



## Cromewell

It's a little mixed. This code produces the exact same behaviour. Just changed the printfs to couts.


		Code:
	

//sort.cpp sorts the index from lowest value to highest value
//
//Adam Holthaus

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>

void sort(double, int);

using namespace std;

void sort(double d_array[], int i_arrSize)
{
    int i_swap;
    double d_temp;
    
    for (int x = 0; x < i_arrSize; x++){
        d_temp = d_array[x];
        i_swap = x-1;
        
        while(d_temp < d_array[i_swap] && i_swap >= 0){
            d_array[i_swap+1] = d_array[i_swap];
            i_swap--;
        }
        
        d_array[i_swap+1] = d_temp;
    }
}

int main(){
    double d_sortMe[] = {1.0,2.0,5.0,3.0,6.0,2.5,1.3};
    double d_stdDev;
    int i_arrSize = sizeof(d_sortMe)/sizeof(double);

    cout << "Original Order" << endl;
    cout << "------------------------" << endl;

    for (int x = 0; x < i_arrSize; x++){
        cout << d_sortMe[x] << endl;
    }

    cout << "------------------------" << endl;
    cout << "Sorted" << endl;
    cout << "------------------------" << endl;
            
    sort(d_sortMe, i_arrSize);
    
    for (int x = 0; x < i_arrSize; x++){
        cout << d_sortMe[x] << endl;
    }

    cout << "------------------------" << endl;
    
    system("pause");
    
    return 0;
}


----------



## Dystopia

Ok, new problem. We have been working on overloading operators. And all as went well until THIS project.

I need to add two fractions, with different denominators. I got the LCD part figured out (actually, I figured that out while posting this and saying "wait a sec" to myself). This is how I am doing the math part (mentally), using these fractions:

1/6 + 7/9 = ?/?

LCD of 6 and 9 = 18

1/6 * 3/3 = 3/18

7/9 * 2/2 = 14/18

Now I can add

3/18 + 14/18 = 17/18

I cannot figure out how to tell the program to multiply the way I did. Obviously I could do that if I wanted, but then I could not enter different values. The values are whatever I put in, I chose the ones that I listed. Here are the function codes:

LCD (works fine for me):



		Code:
	

long rational::lcd(long d2)
{
	long minden, maxden, multiple;
	minden = min(den, d2);
	maxden = max(den, d2);
	multiple = 1;
	while(maxden*multiple%minden !=0)
		multiple++;
	return maxden*multiple;
}


GFC code (I have no idea what to use for what):


		Code:
	

long rational::greatestcommonfactor(long x1, long x2)
{
	long minnum, maxnum, gcf;
	minnum = min(abs(x1), abs(x2));
	maxnum = max(abs(x1), abs(x2));
	gcf = minnum;
	while(maxnum % gcf !=0 || minnum % gcf !=0)
		gcf--;
	return gcf;
}


overloaded operator + code (this is working fine for me):


		Code:
	

rational rational:: operator +(rational fraction_2)
{
	long cden, gfc, x1, x2;
	rational sum;		

	cden =  lcd(fraction_2.den);

	sum.den = cden;

	x1 = num;
	x2 = fraction_2.num;

	gfc = greatestcommonfactor(x1, x2);

		
	sum.num = x1 + x2;

	return sum;
}


Here is my int main. you need to replace my int_main line with yours:


		Code:
	

// lab20.cpp : Defines the entry point for the console application.
//


#include "rational.h"

int _tmain(int argc, _TCHAR* argv[])
{
	rational fraction_1, fraction_2, sum;

	cout <<"Please enter fractions seperated by spaces, numerator and denominator seprated by spaces: ";
	cin >>fraction_1 >>fraction_2;

	sum = fraction_1 + fraction_2;

	cout <<fraction_1 <<endl <<fraction_2 <<endl <<sum <<endl;
	return 0;
}


and in case you want it, the .h file for the rational class:


		Code:
	

// header file to define the rational class
//
//Adam Holthaus, steve05

#include <iostream>
#include <fstream>
using namespace std;

class rational
{
	friend istream& operator >>(istream&, rational&);
	friend ostream& operator <<(ostream&, rational);

private:
	long num, den;

public:
	void reduce();
	long greatestcommonfactor(long, long);
	long lcd(long);
	rational operator +(rational);
};


----------



## Cromewell

31!m!n80r said:


> Ok, new problem. We have been working on overloading operators. And all as went well until THIS project.
> 
> I need to add two fractions, with different denominators. I got the LCD part figured out (actually, I figured that out while posting this and saying "wait a sec" to myself). This is how I am doing the math part (mentally), using these fractions:
> 
> 1/6 + 7/9 = ?/?
> 
> LCD of 6 and 9 = 18
> 
> 1/6 * 3/3 = 3/18
> 
> 7/9 * 2/2 = 14/18
> 
> Now I can add
> 
> 3/18 + 14/18 = 17/18
> 
> I cannot figure out how to tell the program to multiply the way I did. Obviously I could do that if I wanted, but then I could not enter different values. The values are whatever I put in, I chose the ones that I listed. Here are the function codes:



I've been trying but I can't get your code to build, getting a ton of errors. But the general process should be:
Find lowest common denominator.
Find what you need to multiply the fractions by to make them have that denominator. (Divide lowest common denominator by the current denominators)
Multiply the numerators by the respective numbers from the previous step.
Add the numerators together, the new numerator goes over the lowest common denominator.
Reduce your new fraction.


----------



## Dystopia

Cromewell said:


> I've been trying but I can't get your code to build, getting a ton of errors. But the general process should be:
> Find lowest common denominator.
> Find what you need to multiply the fractions by to make them have that denominator. (Divide lowest common denominator by the current denominators)
> *Multiply the numerators by the respective numbers from the previous step.*
> Add the numerators together, the new numerator goes over the lowest common denominator.
> Reduce your new fraction.



That is the only issue I am having right now. The LCD function returns the LCD though, so I won't know what numbers are multiplying. You've given me a couple ideas though, so I'll try them and get back to you. Thanks.


----------



## NyxCharon

If you have a fairly good grasp of java overall, what would be the best way to begin learning c/c++?  What's the best source/book/etc for someone who already understands a language?


----------



## Dystopia

Try using Starting Out With C++: From Control Structures through Objects - 6th edition by Tony Gaddis

Great book, I really like it.


----------



## Troncoso

31!m!n80r said:


> Try using Starting Out With C++: From Control Structures through Objects - 6th edition by Tony Gaddis
> 
> Great book, I really like it.



Yep that's actually the same book I used for my class. considering my class was online I learned everything I know about C++. from that book.


----------



## Cromewell

If I remember correctly, this was the book I used:
http://www.amazon.com/Primer-Plus-5th-Stephen-Prata/dp/0672326973/ref=pd_bxgy_b_text_b


----------



## kobaj

Got a C++ DLL question for you guys. (No doubt this is something simple I'm overlooking.) Anyway, I'm making a DLL following this guide here. And a mix of this nifty code here in my header.

Now the problem comes when importing/referencing/trying to use the DLL I've compiled in a different solution than the one the DLL is in. All the guides I read say to reference a .lib file, but I don't seem to have this file. With a bit of reading, I can make a .lib file (static library as I'm told, ie, a new/different project than the dll project) but then the .dll isn't made.

So am I doing something wrong? (or do you guys need more info the help me out?)


----------



## Cromewell

I haven't built a DLL before, I'll try following the guide and see what happens though.


----------



## Cromewell

Cromewell said:


> I haven't built a DLL before, I'll try following the guide and see what happens though.


I was able to build and link to a DLL using the steps here but a console application using DevC++:
http://msdn.microsoft.com/en-us/library/ms235636(v=VS.90).aspx

How big is your project? Are you able to post your code?


----------



## kobaj

Cromewell said:


> I was able to build and link to a DLL using the steps here but a console application using DevC++:
> http://msdn.microsoft.com/en-us/library/ms235636(v=VS.90).aspx
> 
> How big is your project? Are you able to post your code?



I'm able to build a DLL and link it within my solution. But I'm trying to link to the DLL without it being within my solution. Does that make sense? Or are you supposed to add all DLLs to your solution in order to use them? (ie, there is no way to just use references unless I can get the mythical .lib file working?) I found a way to link DLLs during runtime without a .lib, but I don't have that requirement on this project (ie, it can be done and is preferred at compile time).

Anyway, I'll 2shared the project. DynamicLibrary is the DLL I've made, while Homework4 is the project trying to use DynamicLibrary's DLL. I've deleted all the appropriate .user files so it won't dick with your Visual Studio files (if you use Visual Studio that is...) I know its not commented yet and probably doesn't make a /lick/ of sense, I apologize but I found out it was due Tuesday and was in a HUGE rush...and then I missed the deadline...so I figure I might as well finish it to learn something. 

Long story short, I'm sorry for its un-professional polish and completely understand if you don't want to deal with trying to figure it out.

 /rambling

Anyway, Thank you .


----------



## Cromewell

Unfortunately I don't have visual studio in my development VM. I've opened it in Dev C++, looks like it's close enough for what I need to see 

The general process is build your DLL, add it as a reference to your project and (this is the step I suspect you may be missing) add bst.h to your project to access your DLL class. This header, or cpp file I guess as you could put it anywhere, is where you'd have __declspec(dllimport).

I'll show you my code, the actual process of linking will be a little different than what I need to do though.

DLL File:


		Code:
	

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */


// MathFuncsDll.h

namespace MathFuncs
{
    class DLLIMPORT MyMathFuncs
    {
    public:
        // Returns a + b
        double Add(double a, double b);

        // Returns a - b
        double Subtract(double a, double b);

        // Returns a * b
        double Multiply(double a, double b);

        // Returns a / b
        // Throws DivideByZeroException if b is 0
        double Divide(double a, double b);
    };
}



#endif /* _DLL_H_ */




		Code:
	

// MathFuncsDll.cpp

#include "MathFuncsDll.h"
#include <stdexcept>

using namespace std;

namespace MathFuncs
{
    double MyMathFuncs::Add(double a, double b)
    {
        return a + b;
    }

    double MyMathFuncs::Subtract(double a, double b)
    {
        return a - b;
    }

    double MyMathFuncs::Multiply(double a, double b)
    {
        return a * b;
    }

    double MyMathFuncs::Divide(double a, double b)
    {
        if (b == 0)
        {
            throw new invalid_argument("b cannot be zero!");
        }

        return a / b;
    }
}


Project Referencing DLL:


		Code:
	

// MyExecRefsDll.cpp

#include <iostream>

#include "MathFuncsDll.h"

using namespace std;

int main()
{
    MathFuncs::MyMathFuncs *mathInstance = new MathFuncs::MyMathFuncs();
    double a = 7.4;
    int b = 99;

    cout << "a + b = " <<
        mathInstance->Add(a, b) << endl;
    cout << "a - b = " <<
        mathInstance->Subtract(a, b) << endl;
    cout << "a * b = " <<
        mathInstance->Multiply(a, b) << endl;
    cout << "a / b = " <<
        mathInstance->Divide(a, b) << endl;

    delete mathInstance;

    system("PAUSE");
    return EXIT_SUCCESS;
}


Hope that helps a little.


----------



## kobaj

Cromewell said:


> *snip*



Very peculiar. My professor was saying to reference the header file with brackets like #include <bst> (perhaps thats for those magical .lib libraries.) I'll play around with it some more this weekend.

I think the cruel irony is referencing things in c++ visual studio is a joke. You have to add half a million PATH="5$.903" bull declarations to its build. Whereas C# visual studio its right click > add reference > done.

But yes, I'll try making a mini project this weekend with math functions, slowly getting it working and building up before trying to get this dll working with my main program again.

On a completely unrelated note (homework for my next class): does COFO have an assembly thread?


----------



## Cromewell

Nope, if you have questions you can make a thread and I'll add it to the sticky. It has been a while since I've written any assembly though.


----------



## Strokes

*C++ help*

Hey guys. I have been working on a project that asks the user for a file destination, reads in letters, most characters and punctuation, sorts from greatest to least occurring, then prints out the number of that occurring character (or whatever) and the percent:



		Code:
	

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct valDatFor
	{
	public:	
		double num;
		char ch2;
		double average;
	};

const int fortySix = 46;

void getFileName(ifstream& inFile)
{
	
	cout << "Enter the location of the '.txt' file to be opened:";
	char filename[301];
	cin.getline(filename, 300);

	inFile.open(filename); 
	
	if(inFile.fail() )
	exit(0);
}

void countWords(ifstream& file)
{
	int words = 0;
	const char space = ' ';
	const char tab = '\t';
	const char nully = '\0';
	
	string real;
	
	
	do
	{
    file >> real; 

		if (space || tab || nully)
			words++;

	}	
	while(!file.eof() );
	
	
	cout << "There are " << words << " words in this file\n";
	
	file.clear();
	file.seekg(0, std::ios::beg); // Moves to begining of file

	cout << "Pass return to BoF\n";
}

void countChars(ifstream& file, valDatFor lett_punc_symb[fortySix])
{

	char ch;

	int chCounter = 0;
	
	for(int i = 0; i < fortySix; i++)
	{
		lett_punc_symb[i].num = 0;
	}
	
	lett_punc_symb[0].ch2 = 'a';
	lett_punc_symb[1].ch2 = 'b';
	lett_punc_symb[2].ch2 = 'c';
	lett_punc_symb[3].ch2 = 'd';
	lett_punc_symb[4].ch2 = 'e';
	lett_punc_symb[5].ch2 = 'f';
	lett_punc_symb[6].ch2 = 'g';
	lett_punc_symb[7].ch2 = 'h';
	lett_punc_symb[8].ch2 = 'i';
	lett_punc_symb[9].ch2 = 'j';
	lett_punc_symb[10].ch2 = 'k';
	lett_punc_symb[11].ch2 = 'l';
	lett_punc_symb[12].ch2 = 'm';
	lett_punc_symb[13].ch2 = 'n';
	lett_punc_symb[14].ch2 = 'o';
	lett_punc_symb[15].ch2 = 'p';
	lett_punc_symb[16].ch2 = 'q';
	lett_punc_symb[17].ch2 = 'r';
	lett_punc_symb[18].ch2 = 's';
	lett_punc_symb[19].ch2 = 't';
	lett_punc_symb[20].ch2 = 'u';
	lett_punc_symb[21].ch2 = 'v';
	lett_punc_symb[22].ch2 = 'w';
	lett_punc_symb[23].ch2 = 'x';
	lett_punc_symb[24].ch2 = 'y';
	lett_punc_symb[25].ch2 = 'z';
	lett_punc_symb[26].ch2 = '!';
	lett_punc_symb[27].ch2 = '?';
	lett_punc_symb[28].ch2 = ',';
	lett_punc_symb[29].ch2 = '.';
	lett_punc_symb[30].ch2 = ':';
	lett_punc_symb[31].ch2 = ';';
	lett_punc_symb[32].ch2 = '\'';
	lett_punc_symb[33].ch2 = '\"';
	lett_punc_symb[34].ch2 = '@';
	lett_punc_symb[35].ch2 = '#';
	lett_punc_symb[36].ch2 = '$';
	lett_punc_symb[37].ch2 = '%';
	lett_punc_symb[38].ch2 = '&';
	lett_punc_symb[39].ch2 = '*';
	lett_punc_symb[40].ch2 = '(';
	lett_punc_symb[41].ch2 = ')';
	lett_punc_symb[42].ch2 = '+';
	lett_punc_symb[43].ch2 = '=';
	lett_punc_symb[44].ch2 = '/';
	lett_punc_symb[45].ch2 = '-';

	lett_punc_symb[46].num = 0;
	lett_punc_symb[46].ch2 = '~';

	cout << "Pass struct assignment\n";
	
	do
	{
		file >> ch;
		
		switch(ch)
		{
			case 'a':
			case 'A':
			lett_punc_symb[0].num++;
			break;

			case 'b':
			case 'B':
			lett_punc_symb[1].num++;
			break;
			
			case 'c':
			case 'C':
			lett_punc_symb[2].num++;
			break;

			case 'd':
			case 'D':
			lett_punc_symb[3].num++;
			break;

			case 'e':
			case 'E':
			lett_punc_symb[4].num++;
			break;

			case 'f':
			case 'F':
			lett_punc_symb[5].num++;
			break;

			case 'g':
			case 'G':
			lett_punc_symb[6].num++;
			break;

			case 'h':
			case 'H':
			lett_punc_symb[7].num++;
			break;

			case 'i':
			case 'I':
			lett_punc_symb[8].num++;
			break;

			case 'j':
			case 'J':
			lett_punc_symb[9].num++;
			break;

			case 'k':
			case 'K':
			lett_punc_symb[10].num++;
			break;

			case 'l':
			case 'L':
			lett_punc_symb[11].num++;
			break;

			case 'm':
			case 'M':
			lett_punc_symb[12].num++;
			break;

			case 'n':
			case 'N':
			lett_punc_symb[13].num++;
			break;

			case 'o':
			case 'O':
			lett_punc_symb[14].num++;
			break;

			case 'p':
			case 'P':
			lett_punc_symb[15].num++;
			break;

			case 'q':
			case 'Q':
			lett_punc_symb[16].num++;
			break;

			case 'r':
			case 'R':
			lett_punc_symb[17].num++;
			break;

			case 's':
			case 'S':
			lett_punc_symb[18].num++;
			break;

			case 't':
			case 'T':
			lett_punc_symb[19].num++;
			break;

			case 'u':
			case 'U':
			lett_punc_symb[20].num++;
			break;

			case 'v':
			case 'V':
			lett_punc_symb[21].num++;
			break;

			case 'w':
			case 'W':
			lett_punc_symb[22].num++;
			break;

			case 'x':
			case 'X':
			lett_punc_symb[23].num++;
			break;

			case 'y':
			case 'Y':
			lett_punc_symb[24].num++;
			break;

			case 'z':
			case 'Z':
			lett_punc_symb[25].num++;
			break;

			case '!':
			lett_punc_symb[26].num++;
			break;
			
			case '?':
			lett_punc_symb[27].num++;
			break;

			case ',':
			lett_punc_symb[28].num++;
			break;

			case '.':
			lett_punc_symb[29].num++;
			break;

			case ':':
			lett_punc_symb[30].num++;
			break;

			case ';':
			lett_punc_symb[31].num++;
			break;

			case '\'':
			lett_punc_symb[32].num++;
			break;

			case '\"':
			lett_punc_symb[33].num++;
			break;

			case '@':
			lett_punc_symb[34].num++;
			break;

			case '#':
			lett_punc_symb[35].num++;
			break;

			case '$':
			lett_punc_symb[36].num++;
			break;

			case '%':
			lett_punc_symb[37].num++;
			break;

			case '&':
			lett_punc_symb[38].num++;
			break;

			case '*':
			lett_punc_symb[39].num++;
			break;

			case '(':
			lett_punc_symb[40].num++;
			break;

			case ')':
			lett_punc_symb[41].num++;
			break;

			case '+':
			lett_punc_symb[42].num++;
			break;

			case '=':
			lett_punc_symb[43].num++;
			break;

			case '/':
			lett_punc_symb[44].num++;
			break;

			case '-':
			lett_punc_symb[45].num++;
			break;
			
			default:
			break;
		}
	}
	while(!file.eof() );
	
	cout << "Pass switch\n";
}


void sortChars(valDatFor lett_punc_symb[fortySix])
{
	int out, loc, temp;

	for(out = 1; out < 45; out++)
		if(lett_punc_symb[out].num < lett_punc_symb[out - 1].num)
		{
			temp = lett_punc_symb[out].num;
			loc = out;

			do
			{
				lett_punc_symb[loc].num = lett_punc_symb[loc - 1].num;
				loc--;
			}
			while (loc > 0 && lett_punc_symb[loc - 1].num > temp);

			lett_punc_symb[loc].num = temp;
		}

}

void printCount(valDatFor lett_punc_symb[fortySix])
{
	for(int i = 0; i < 46; i++)
	{
		lett_punc_symb[46].average += lett_punc_symb[i].num;
	}
	
	ofstream outFile;
	
	outFile.open("C:\\Users\\Strokes\\Desktop\\Results.txt");

	outFile << "Letter:		Number:		  Percent:		\n";
	
	for(int i = 0; i < 46; i++)
	{
		outFile << "        " << lett_punc_symb[i].ch2 << "		    ";
		outFile << lett_punc_symb[i].num << "			" << lett_punc_symb[i].num / lett_punc_symb[46].average << "%" << endl;

	}

	cout << "Letter:		Number:		  Percent:		\n";
	
	for(int i = 0; i < 46; i++)
	{
		cout << "        " << lett_punc_symb[i].ch2 << "		    ";
		cout << lett_punc_symb[i].num << "			" << lett_punc_symb[i].num / lett_punc_symb[46].average << "%" << endl;

	}

}

int main()
{
	ifstream file;
	
	getFileName(file);
	
	countWords(file);
	
	valDatFor lett_punc_symb[fortySix];
	
	countChars(file, lett_punc_symb);

	sortChars(lett_punc_symb);

	printCount(lett_punc_symb);
	
	return 0;
}



Now the trouble is it crashes in the middle of running. I think it makes it to the switch structure, but crashes there. There are no syntax errors because it complies fine. Is there anything I'm missing in that switch structure?


----------



## Cromewell

I've moved your post to the C++ thread.

It's failing on line 125 (file >> ch, just before the switch). It's a segmentation fault, calling certain file member functions seems to cause it, I can't get anything about the location of the file pointer. The file reports that it is open but I can't get anything else from it.


----------



## mihir

kobaj said:


> Very peculiar. My professor was saying to reference the header file with brackets like #include <bst> (perhaps thats for those magical .lib libraries.) I'll play around with it some more this weekend.
> 
> I think the cruel irony is referencing things in c++ visual studio is a joke. You have to add half a million PATH="5$.903" bull declarations to its build. Whereas C# visual studio its right click > add reference > done.
> 
> But yes, I'll try making a mini project this weekend with math functions, slowly getting it working and building up before trying to get this dll working with my main program again.
> 
> On a completely unrelated note (homework for my next class):* does COFO have an assembly thread?*




Do you already know a bit of assembly??
Which processor will you be working on?(32bit or 16bit)
Any modern Day processor or something like 8086/8085.
The best way to learn Assembly is writing programs in C/C++ and saving the temporary files at the time of compilation and then studying those files with respect to the original .c file.

And how much do you already know about the segment registers?


----------



## Bananapie

Maybe my topic belonged more here.

I am Computer Science major who is working in JAVA right now. Learned GUI and up to Linked List and some other stuff. Classes and whatnot.

I assume as I progress, it will be required to know C++.

This summer, I am wanting to teach myself some C++, and try and get a small grasp, or as much as I can get, before I transfer this coming fall.

Does anyone have any books, or tutorial pages to work off of? 
As well, what good compilers would one use for C++?

I work with NetBeans in JAVA.


----------



## Dystopia

Bananapie said:


> Maybe my topic belonged more here.
> 
> I am Computer Science major who is working in JAVA right now. Learned GUI and up to Linked List and some other stuff. Classes and whatnot.
> 
> I assume as I progress, it will be required to know C++.
> 
> This summer, I am wanting to teach myself some C++, and try and get a small grasp, or as much as I can get, before I transfer this coming fall.
> 
> Does anyone have any books, or tutorial pages to work off of?
> As well, what good compilers would one use for C++?
> 
> I work with NetBeans in JAVA.



Bloodshed works good for Java, though I really like Visual Studio 2010 if you can afford it. 

This is the book I used, really liked it:http://www.amazon.com/Starting-Out-...=sr_1_3?ie=UTF8&s=books&qid=1305063802&sr=8-3

If you are interested, I'd sell you my book for cheap, its got some water damage and applesauce damage....but all the pages are there. PM me if you are interested.


----------



## wolfeking

Im using the book linked below. mainly cause its free. Seems to be good, but im only on page 20 some right now. 

http://greenteapress.com/thinkcpp/thinkCScpp.pdf

And I will second the question on the compilers. Are there any freeware compilers that work fairly well with C++, preferably in linux?


----------



## wolfeking

Ok. Getting a little confused here. Working in simple C++. Trying to use a online compiler to convert the simple program "hello world", but I am getting a bunch of errors with it. 

The compiler I am using right now (at school) is http://www.comeaucomputing.com/tryitout/.   

The original program code is:


		Code:
	

#include <iostream.h>
// main: generate some simple output
void main ()
{
cout << "Hello, world." << endl;
return 0
}

the first error says the <iostream.h> isn't valid, and to use <iostream>. Ok, so I corrected that to 
	
	




		Code:
	

 #include <iostream>
// main: generate some simple output
void main ()
{
cout << "Hello, world." << endl;
return 0
}

and now I am getting an error that says 





> "ComeauTest.c", line 3: error: return type of function "main" must be "int"
> So use int main() OR int main(int argc, char *argv[])
> void main ()
> ^
> 
> "ComeauTest.c", line 5: error: identifier "cout" is undefined,
> Perhaps use "std::cout", or "using namespace std;"?
> Did you #include <iostream>?"
> cout << "Hello, world." << endl;
> ^
> 
> "ComeauTest.c", line 5: error: identifier "endl" is undefined,
> Perhaps use "std::endl", or "using namespace std;"?
> Did you #include <iostream>?"
> cout << "Hello, world." << endl;
> ^
> 
> "ComeauTest.c", line 6: error: return value type does not match the function type
> return 0
> ^
> 
> "ComeauTest.c", line 7: error: expected a ";" (perhaps on the previous statement)
> }
> 
> ^cout << "Hello, world." << endl;
> return 0
> }


can someone help me fix this, so that I can actually have achieved something today?


----------



## Cromewell

wolfeking said:


> Ok. Getting a little confused here. Working in simple C++. Trying to use a online compiler to convert the simple program "hello world", but I am getting a bunch of errors with it.
> 
> The compiler I am using right now (at school) is http://www.comeaucomputing.com/tryitout/.
> 
> The original program code is:
> 
> 
> Code:
> 
> 
> #include <iostream.h>
> // main: generate some simple output
> void main ()
> {
> cout << "Hello, world." << endl;
> return 0
> }
> 
> the first error says the <iostream.h> isn't valid, and to use <iostream>. Ok, so I corrected that to
> 
> 
> 
> 
> 
> 
> Code:
> 
> 
> #include <iostream>
> // main: generate some simple output
> void main ()
> {
> cout << "Hello, world." << endl;
> return 0
> }
> 
> and now I am getting an error that says can someone help me fix this, so that I can actually have achieved something today?



The errors are telling you exactly what is wrong:


		Code:
	

 #include <iostream>
// main: generate some simple output

using namespace std; // <------- added namespace
int main () //<-----changed void to int
{
cout << "Hello, world." << endl;
return 0; //<---added semicolon
}


----------



## wolfeking

sorry, double post.


----------



## wolfeking

thanks cromewell. 
Its was a success that time. 

And sorry. Sometimes I dont have the patience to read things, and my english skills arent that good either.


----------



## ScottALot

Newbie here. I want to learn C++, so I downloaded the Visual C++ Express 2010 from Microsoft, ordered a C++ book (http://cgi.ebay.com/ws/eBayISAPI.dl...38&ssPageName=ADME:L:OC:US:1123#ht_500wt_1202)

I just don't know where to go from here. No classes at school... not really any resources in the city I live in.


----------



## Troncoso

Well, I can't connect to ebay to see the book you have, but if it's more or less a c++ programming textbook the best thing to do is just read it. If you are actually interested in programming, you will absorb the information. When it tells you to do an exercise or example, go beyond that. Once you've done it, add on to it, figure out ways to make the program work the way you think it should. Learning to program is like learning a new language. You don't have to to be able to pull any function from the top of your head, but if you know how to use them and the syntax for the language, you'll have no problems. But, for real the book is best place to start. You really don't find information organized in such a way on the web.


----------



## Dystopia

ScottALot said:


> Newbie here. I want to learn C++, so I downloaded the Visual C++ Express 2010 from Microsoft, ordered a C++ book (http://cgi.ebay.com/ws/eBayISAPI.dl...38&ssPageName=ADME:L:OC:US:1123#ht_500wt_1202)
> 
> I just don't know where to go from here. No classes at school... not really any resources in the city I live in.



Well, you have a beginner book. I don't know what compiler that book uses, but if it isn't VS, then there is a line you need to add. Anyway, just read from page one, go from there, should get you going. Depending on how serious you are on learning C++ (hobby, or possible career?), you could look into dual enrollment so that you can also go to college for C++ at the same time.


----------



## S.T.A.R.S.

If you want to learn C++,you must be prepared on long studying and a lot of time spent in the front of the book and the monitor lol.Same appplies for a chair lol.

Since you are a beginner,why not start with VB?
VB is not bad and you can make whatever you want in it just like in C++.And if someone tells you that's impossible,don't listen to that.I know few people who made powerful 3D applications in VB 6.0 so that tells you everything.

C++ is too hard for a beginner trust me.There are just too many things you won't understand and if you keep reading,but did not understand first 20 pages then it is a very small chance you will understand anything on the next pages since it is getting harder and harder as you are reading.

I recommend you to start learning easier language and once you start understanding the logic and syntax then you can move to harder language.
I also started with VB long time ago and even VB was hard for me back then so imaginate how C++ would be hard for me.Same applies for you.
After a year I went to C# which was harder one and after it I went to C++ which was also harder one.
And now after a long time of studying I fully understand all three of them.

I was also like you and I wanted C++ immediately at the beginning too,but as soon as started reading the book about it,I just gave up because it did not make any sense to me back then many years ago.

What I am trying to say is that it is a lot better to start with something easier made for the beginners then immediately jump to C++ and expect you will understand everything because you won't lol.

I know many people who immediately go to C++.I ask them why and they simply tell me:"I heard it is the best one."
But what they did not hear is that you need some knowledge in order to understand it and also they did not hear that simple VB can be used to make same things just like in C++ if you know how.

My recommendation for you is VB 2010.Install it and start from the stratch.And by the stratch I mean on something so simple like a message which will appear when you click the button:

When the user clicks the button,do the following action:

MessageBox.Show("Hello Mr. ScotALot and welcome to the programming world!")

As you can see above,I used words which are case sensitive,dots,brackets and quotes.And these are just SOME of the most basic things you need to understand in order to even move on.Because DOTS,BRACKETS,QUOTES and so on...are used in many other areas too.
Here we also have the key words and many many many other things I did not even mention which you need to understand in order to start udnerstanding the logic of the programming.Once you do then you will start understanding the C++ too.

Trust me C++ is just too hard to understand if you do not even know the basics.You can try of course it is your choice,but soon you will realize that it is not that easy lol.


----------



## Troncoso

....Don't try to scare people away from something they want to learn. If you find a beginner's book to C++, it'll go over the basics of what a variable is, what a function is, what syntax is, etc. The thing that really makes C++ harder to deal with is the memory management, but in the beginning that's barely something to worry about.
Seriously. C++ is a great language to learn. If you get comfortable with it first, then learning other languages will be vary simple.

I would suggest learning java possibly first, thought. It's syntax  is very similar to C++ (just different keywords) BUt you don't have to worry so much about memory management. There is also a compiler for java called "BlueJ" It makes programming very simple so you can focus on getting your syntax right and developing proper programming techniques. I recommend that as a good place to start.


----------



## S.T.A.R.S.

LoL I am not trying to scare anyone haha!

I was just saying that the C++ is not that easy.Still if the book he has is good then it will be a lot easier.Only he has to be prepared for a lot of studying.

Anyway good luck ScotALot!


----------



## Thanatos

Any idea as to why this isn't working for me? I'm getting a squiggly underneath 'sqrt'.



		Code:
	

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
	int x1;
	int x2;
	int y1;
	int y2;

	char choice = 'y';
	while (choice == 'y')
	{
		cin >> x1;
		cin >> x2;
		cin >> y1;
		cin >> y2;

		cout << sqrt((x1-y1)^2 + (x2-y2)^2);
		cin >> choice;
	}
	return 0;
}

EDIT: Got it, change int to double. but now, when i try to run it, it says cannot find the path specified. help???


----------



## Troncoso

Green dog252 said:


> Any idea as to why this isn't working for me? I'm getting a squiggly underneath 'sqrt'.
> 
> 
> 
> Code:
> 
> 
> #include <iostream>
> #include <math.h>
> using namespace std;
> 
> int main()
> {
> int x1;
> int x2;
> int y1;
> int y2;
> 
> char choice = 'y';
> while (choice == 'y')
> {
> cin >> x1;
> cin >> x2;
> cin >> y1;
> cin >> y2;
> 
> cout << sqrt((x1-y1)^2 + (x2-y2)^2);
> cin >> choice;
> }
> return 0;
> }
> 
> EDIT: Got it, change int to double. but now, when i try to run it, it says cannot find the path specified. help???



I could be wrong but I thing its



> #include "math.h"


----------



## Thanatos

would changing this make it find the path specified?


----------



## Troncoso

Green dog252 said:


> would changing this make it find the path specified?



Well, yeah, if you don't have the syntax correct, it won't properly register the import statement and won't import the math class.

It's been a while since I've used C++. I just remember using <> for standard libraries and " " for anything that ended in .h, haha

also, if you could be more specific with the error. I'm not quite sure what can't be specified


----------



## mihir

Troncoso said:


> Well, yeah, if you don't have the syntax correct, it won't properly register the import statement and won't import the math class.
> 
> It's been a while since I've used C++. I just remember using <> for standard libraries and " " for anything that ended in .h, haha
> 
> also, if you could be more specific with the error. I'm not quite sure what can't be specified



include "math.h" should also work.
Mainly double quotes are used to include custom header files, but it also works for the standard header files.
Just make sure that you have the math.h header file in the proper directory.
But it might be a compiler thing, so just to be safe try <math.h>


----------



## Thanatos

When i press ctrl+F5, prompt comes up and says 'Cannot find path specified, press any key to continue......'

Hey, I'm a fourteen year old in a town with a population of like 1000. I'm allowed to make some stupid mistakes.


----------



## mihir

Green dog252 said:


> When i press ctrl+F5, prompt comes up and says 'Cannot find path specified, press any key to continue......'
> 
> Hey, I'm a fourteen year old in a town with a population of like 1000. I'm allowed to make some stupid mistakes.



What compiler are you using?


----------



## TrainTrackHack

You should be using just cmath (without .h) instead of math.h. The .h headers are there mainly for backward compatibility with C as well as older pre-namespaces C++ programs, these days you should try to avoid using standard headers with a .h extension in your C++ programs (and I mean only standard headers, for libraries and your own header files it's still customary to use the extension).


----------



## Thanatos

visual c++ 2010.


----------



## Thanatos

This will probably help.


----------



## TrainTrackHack

That's beyond weird. I can't think of any reason it would do that other than either you're actually missing some standard header files (in which case I would reinstall, you could be missing all sorts of things) or some really tricky project setting that I don't know of gone wrong.

Though I notice you hadn't saved the file in that screenshot... I don't use Visual C++ myself so I don't know for sure but some IDEs (at least in the past) don't compile modified files unless you've actually saved them; making a change and simply recompiling would cause the old source to be compiled.


----------



## Troncoso

My first step would be simply removing and installing VS. I will tell you, if you are in school Microsoft offers the full version of Visual Studio. Not sure, if that's what you have or not, but yeah, that's an option.


----------



## Thanatos

hackapelite said:


> Though I notice you hadn't saved the file in that screenshot... I don't use Visual C++ myself so I don't know for sure but some IDEs (at least in the past) don't compile modified files unless you've actually saved them; making a change and simply recompiling would cause the old source to be compiled.



I believe that CTRL + F5 saves it and compiles it. but thanks for all the help, I'll reinstall it once my internet cycle starts over. It has a 5 Gig cap, and its nearly done with.


----------



## S.T.A.R.S.

From the picture you gave us,it seems like some of your project files are simply missing and that of course results in a project not working no matter how good the programming code is.Go into your project directory and make sure that all the files are there on their correct locations.

Also be sure that IDE and OS are not corrupted and that their files are not missing because if they do,that will also result in your projects not working correctly.

You can try 2 things before repairing an OS and IDE:

1. Click BUILD ---> REBUILD SOLUTION.If the OUTPUT window reports that everything has been built correctly and that nothing is skipped and that nothing has failed then click the DEBUG button and see if your project works correctly now.

2. Make new C++ project and carefully copy and paste your programming code into the newly created project and see if application is now working correctly.

If the result is the same after these 2 things,try writing a VERY simple line of code which shows a simple text such as HELLO.If even that doesn't work then something is definetely wrong with your IDE data or/and OS data.In that case repair or reinstall IDE or/and OS.

These things can happen for numerous reasons.6 years ago I had a similar problem in C#.The code I always used always worked and one day it gave me blank error and did not want to compile at all.At the end I found out it was a corrupted OS DLL file that was causing the problem and not me lol.Since most of the programming code functions rely on IDE or/and OS DLL data,if that DLL data is damaged or missing,your projects will simply not work correctly no matter how good the programming code written by you is.




Cheers!


----------



## HazzaHnoob

So I started a module of lectures and labs on C this week, and I was wondering if anyone has any cool .c source codes that would be interesting to look at??

Also, it seems like this thread so far is mainly C++, any other people just starting to learn to program and starting with C??


----------



## S.T.A.R.S.

C is a very old language.More and more people are moving to C++ and C# since they are newer versions of C.


----------



## HazzaHnoob

S.T.A.R.S. said:


> C is a very old language.More and more people are moving to C++ and C# since they are newer versions of C.



I realise that, but I don't dictate my course modules...


----------



## Cromewell

Generally C is taught as a stepping point before moving on to C++. C still has it's uses though (embedded code is fun).

All I ever really did in C was some console programs do learn the basics of the language. We did mess with BGI for a bit and made nibbles, it's an old qbasic game if anyone remembers it.


----------



## S.T.A.R.S.

Everyone has their favorite language which they use most of the time.
And which one they will use to start learning this and which one they will use later is completely up to them.

For example I started with old VB,but that does not mean I should still use it now lol.Now I use mostly C# and C++ here and there if I decide to translate my C# applications to C++.

Like I said...it completely depends on the person what language he/she will use.The goal is the same: MAKE GOOD SOFTWARE AND SELL IT!
People who buy your software do not ask in what language it was made in lol




Cheers!


----------



## HazzaHnoob

S.T.A.R.S. said:


> Now I use mostly C# and C++ here and there if I decide to translate my C# applications to C++.



Wait, why would you want to translate your applications? Surely once they are compiled anyone can run them anyway? Or would you only do it if you wanted to work with another programmer but they prefer C++??

Also, is it easy to translate, say, C applications into C# or C++?


----------



## S.T.A.R.S.

HazzaHnoob said:


> Wait, why would you want to translate your applications? Surely once they are compiled anyone can run them anyway? Or would you only do it if you wanted to work with another programmer but they prefer C++??
> 
> Also, is it easy to translate, say, C applications into C# or C++?



LoL don't worry.I do not translate applications from C# to C++ or from C++ to C# very often anyway.I do that only if a team prefers that language or if I am bored as hell like I am right now lol because my main computer on which I am programming is scanning right now as I am writing this and it will take approximately 6 hours or more to finish so I have nothing better to do anyway lol xD

As for your question: Is it EASY to convert C into C# or C++...
Well that term EASY really depends on your knowledge lol.For me it's not hard,but for someone who just started learning this it is going to be mission impossible lol.That is why all beginners should use VB.It's short,simple and easy to understand 

Unforcenately there is no really a C to C# converter which will do ALL the job for you.

For example if you want to translate C application into C# application,the best way is to do it like this:

-Copy the C code into the C++ compiler such as Visual C++ IDE...
-Compile the application and then correct the errors that occured.And believe me,there WILL be errors lol.There always are xD...
-Add/remove/change some programming code as neccessary...
-Compile again and make sure there are no syntax,runtime and logical errors...
-Test the application to make sure it is working properly...
-Now once the application fully works as 100% C++ application,you can turn it into a C# application on few ways:

--->Use Salamander .NET converter to convert the C++ code into the C# code and then copy that converted code into the C# compiler such as Visual C# IDE,compile it and make sure it's working properly.If there are errors of any kind,correct them...

--->Use Spices .NET converter to convert the C++ code into the C#  code and then copy that converted code into the C# compiler such as  Visual C# IDE,compile it and make sure it's working properly.If there  are errors of any kind,correct them...

--->Or the hardest way is to copy the C++ code into the C# compiler such as Visual C# IDE directly and rechange and correct the entire code manually which is pain in the ass lol.This is how I do it.It's not really that hard if you know how to do it,but you will lose a lot of time believe me xD
And that is because each method,string,int,bool values,brackets,points,events,controls,fields,references and all other things needs to be rewritten manually to make them to work as a C# application.It might seem to be a lot of work,but for example if you need to rewrite the SAME thing on many places such as:

Application::Exit();

to

Application.Exit();

or

this->Text="This sucks!";

to

this.Text="This sucks!";


Then in that case you can always use the REPLACE ALL function in IDE to save some little time instead rewriting all those same things manually.Still if the application is big and has many lines of code,in most cases REPLACE ALL will not be enough lol and you will need to do many changes manually.That is why there are C++ to C# converters.Because they do most of the job for you so it saves you a lot of torture lol.

Still I prefer to do it manually.I guess I am just used to do it that way and at least I am 100% sure that I did not miss anything.

For example my UAC keyboard spy version 1.0 project on which I am working right now has approximately 700 pages (plus approximately 200 more pages which I need to finish this month) full of C# code and there are a LOT LOT LOT different things inside.So now just imaginate how big torture it would be to manually translate all that into C++ lol.It would be a HUGE pain in the ass believe me
Same applies for C++ into C#.It is huge torture on both ways believe me lol.

Yes it's true that once applications are compiled in one language then anyone can run them,but like I said...I translate them to kill the boring time I am having right now lol.Sometimes it's cool to have software you made in two languages  They will both of course work the same,but it's cool lol...I am crazy I know 




Cheers!


----------



## HazzaHnoob

Wowee, that was a long reply!!

I'm definitely a long way from writing whole, useful, applications in any language, let alone translating them, but from all that you said, it sounds like it would almost be easier to just rewrite the whole thing?

Our lecturer had us save our source file as .cpp in one exercise to show that it wouldn't compile, and I figure that's because there a basic difference in how you start a C++ program... Like are the libraries specified differently? Or is the function (the main () bit...) done differently?


----------



## TrainTrackHack

There are a few differences in the language, the only two I can think of right now are C allows implicit casting of pointers and C requires an instance of a struct to be declared as "struct Typename instancename" instead of "Typename instancename" that's done in C++ (though in C typedefs are generally used to replicate this behaviour). There are others too, but most of them are trivial - however, it does mean that you can't always just convert straight C into C++ without making some changes even though C++ is mostly backwards compatible with C.

As for rewriting stuff that you already have in C, you can use C source files in C++ projects easily and usually there are no difficulties - as long as the compiler knows that they're C files rather than C++ and there are no name collisions you should be fine. Using C code in C# (or any managed language like others in the .NET family or Java for that matter) is trickier and you'll either have to rewrite or use something like JNI (no idea if .NET has an equivalent, though I would imagine it does).

I'll also point out that despite its name, C# is nothing like C save for basic constructs that exist in nearly all languages and curly braces. I'd say it's closer to Java than either C or C++.


----------



## S.T.A.R.S.

HazzaHnoob said:


> I'm definitely a long way from writing whole, useful, applications in any language, let alone translating them, but from all that you said, it sounds like it would almost be easier to just rewrite the whole thing?



Depends on how big your program is.If it has let's say 3 pages then it is of course easier to write it whole in C++,but if it has let's say 700 pages then it is torture on both ways,but it is still easier to just copy and paste the code and fix bigs manually.It WILL take a long time,but it will be definetely shorter than writing the whole thing manually again believe me


----------



## Ankur

Hey guys I started a project in C language after finishing C# projects. I'm using visual studio 2008 for this C project. My question is how to debug this C language in this software? When I put a breakpoint and try running the codestep by step then it goes through hundreds of lines of codes that included .h and function definition files. I just want to debug my .C file. Can some one tell me how?


----------



## Cromewell

Try using step over unless the function call you are on is something you have written then step into is ok.


----------



## Ankur

Can anyone tell me which is the best book for x86 assembly?
I have lots of projects on it in college. Can anyone tell me good book which starts from basics and advance.


----------



## Cromewell

I used this one http://www.asmirvine.com/asm/index.htm I thought it was pretty good.


----------



## Troncoso

How do I properly pass an array and change it's value in C?

I have this. It gives me a segfault. I'm trying to get it to scan integers from the file to the array that's declared in main.



		Code:
	

int main() {
    int v[NUM_ELEMENTS];
    int n; 
    int min;
    int max;
    double mean;
       
    getNums(v, &n);
    calcMin (v, n, &min);
    calcMax (v, n, &max);
    calcMean (v, n, &mean);
    return 0;
}

void getNums(int v, int *n) {
    FILE *datafile;
    datafile = fopen (FNAME, "r");
    int count = 0;
    while (!feof (datafile)) {
        int next;
        fscanf (datafile, "%d", next);
        v = next;
        count++;
    }
    *n = count;
    printf ("%d\n", count);
}


NOTE: I'm required to use fscanf as well as declaring all my variables in main.


----------



## TrainTrackHack

Firstly, you're passing an int rather than a pointer to an int which is what I assume you want (&next instead of just next), that's probably what's causing the segfault. I also don't see what you're using v in getNums for - you're assigning it values without ever reading it.


----------



## Troncoso

I just posted the code that actually compiled without error. I know it's not right. Here is exactly what is suppose to happen in getNums:

send v and n (by reference) to getNums
Create a file pointer and open a file for reading (contains a list of ints)
While not at the end of the file:
-----Read an integer from the file into the v array element at position count
-----update count
set n equal to count


So essentially, I have to pass in an array and an int and change their values.


----------



## kobaj

Troncoso said:


> I just posted the code that actually compiled without error. I know it's not right.
> 
> So essentially, I have to pass in an array and an int and change their values.





hackapelite said:


> Firstly, you're passing an int rather than a pointer to an int which is what I assume you want (&next instead of just next), that's probably what's causing the segfault. I also don't see what you're using v in getNums for - you're assigning it values without ever reading it.



Hackapelite answered your question .



		PHP:
	

#include <iostream>
using namespace std;

//pass in the array with *
//pass by reference with &
void function(int *my_array, int &my_value)
{
	my_array[0] = 10; //access the array
	my_array[3] = 2; //access the array
	
	my_value = 6; //access the variable
}

int main()
{
	int v[10]; //make array
	int x; //make variable
	function (v, x); 

	cout << v[0] << ", " << v[3] << endl; //outputs 10, 2
	cout << x << endl; //outputs 6
}


----------



## Troncoso

kobaj said:


> Hackapelite answered your question .



He didn't really, though. The next variable is set to the value read by fscanf. Then next is added to the array as an element. I don't see why I need a pointer for the next variable.

And The only thing getNums is suppose to do is put values into the array, as well as count the number of elements that are put in.

Unless I misunderstood. And it's your examples like yours that is throwing me off. Every time I look at a different example for the same thing, it always looks different. Everyone puts their asterisks and ampersands in different places. I formatted mine just like you did, and it didn't work. Are C++ pointers the same as C?


----------



## kobaj

Troncoso said:


> He didn't really, though. The next variable is set to the value read by fscanf. Then next is added to the array as an element. I don't see why I need a pointer for the next variable.
> 
> And The only thing getNums is suppose to do is put values into the array, as well as count the number of elements that are put in.
> 
> Unless I misunderstood. And it's your examples like yours that is throwing me off. Every time I look at a different example for the same thing, it always looks different. Everyone puts their asterisks and ampersands in different places. I formatted mine just like you did, and it didn't work. Are C++ pointers the same as C?



Oh man, I'm sorry, I didn't realize you were doing this in C. And I do admit, everyone uses pointers (* and &) differently, which is confusing.

In which case my corrected code would be, 


		PHP:
	

#include <stdio.h>

void function(int *my_array, int *my_value)
{
    my_array[0] = 10; //access the array
    my_array[3] = 2; //access the array
    
    *my_value = 6; //access the variable
}

int main()
{
    int v[10]; //make array
    int x; //make variable
    function (v, &x); 

	printf("%i", v[0]); //prints 10
	printf("%i", x); //prints 6.
}


Anyway, you need to walk through your code better to understand why its not working.



		PHP:
	

//you are saying pass in an int, and a pointer to an int.
void getNums(int v, int *n) {

//so right now, v is a single integer (its actually a copy) and n is a pointer to an integer.
//this v will be destroyed at the end of this method.

    FILE *datafile; 
    datafile = fopen (FNAME, "r");
    int count = 0;

    while (!feof (datafile)) {
        int next;
        fscanf (datafile, "%d", next); //you're only passing by value here
        v = next; //you're setting the single v integer over and over again to the next value
        count++;
    }
    *n = count; //this line is correct.
    printf ("%d\n", count);
}


I have not tested the below, but this is probably what you're wanting.



		PHP:
	

int main() {
    int v[NUM_ELEMENTS];
    int n; 
    int min;
    int max;
    double mean;
       
    getNums(v, &n);
    calcMin (v, n, &min);
    calcMax (v, n, &max);
    calcMean (v, n, &mean);
    return 0;
}

//pass a pointer to v and n.
void getNums(int *v, int *n) {

//so at this point v and n are both pointers.
//great thing about c (and confusing as heck) pointers can act as arrays
//this gets really stupid confusing when you find out char and c strings are also just (null terminated) pointers thus arrays as well...

    FILE *datafile;
    datafile = fopen (FNAME, "r");
    int count = 0;
    while (!feof (datafile)) {
        int next;
        fscanf (datafile, "%d", &next); //you want to pass the address here, not the value. 

        v[count] = next; //this sets the value inside the array
        count++;
    }
    *n = count;
    printf ("%d\n", count);
}


----------



## mihir

kobaj said:


> Oh man, I'm sorry, I didn't realize you were doing this in C. And I do admit, everyone uses pointers (* and &) differently, which is confusing.
> 
> In which case my corrected code would be,
> 
> 
> PHP:
> 
> 
> #include <stdio.h>
> 
> void function(int *my_array, int *my_value)
> {
> my_array[0] = 10; //access the array
> my_array[3] = 2; //access the array
> 
> *my_value = 6; //access the variable
> }
> 
> int main()
> {
> int v[10]; //make array
> int x; //make variable
> function (v, &x);
> 
> printf("%i", v[0]); //prints 10
> printf("%i", x); //prints 6.
> }
> 
> 
> Anyway, you need to walk through your code better to understand why its not working.
> 
> 
> 
> PHP:
> 
> 
> //you are saying pass in an int, and a pointer to an int.
> void getNums(int v, int *n) {
> 
> //so right now, v is a single integer (its actually a copy) and n is a pointer to an integer.
> //this v will be destroyed at the end of this method.
> 
> FILE *datafile;
> datafile = fopen (FNAME, "r");
> int count = 0;
> 
> while (!feof (datafile)) {
> int next;
> fscanf (datafile, "%d", next); //you're only passing by value here
> v = next; //you're setting the single v integer over and over again to the next value
> count++;
> }
> *n = count; //this line is correct.
> printf ("%d\n", count);
> }
> 
> 
> I have not tested the below, but this is probably what you're wanting.
> 
> 
> 
> PHP:
> 
> 
> int main() {
> int v[NUM_ELEMENTS];
> int n;
> int min;
> int max;
> double mean;
> 
> getNums(v, &n);
> calcMin (v, n, &min);
> calcMax (v, n, &max);
> calcMean (v, n, &mean);
> return 0;
> }
> 
> //pass a pointer to v and n.
> void getNums(int *v, int *n) {
> 
> //so at this point v and n are both pointers.
> //great thing about c (and confusing as heck) pointers can act as arrays
> //this gets really stupid confusing when you find out char and c strings are also just (null terminated) pointers thus arrays as well...
> 
> FILE *datafile;
> datafile = fopen (FNAME, "r");
> int count = 0;
> while (!feof (datafile)) {
> int next;
> fscanf (datafile, "%d", &next); //you want to pass the address here, not the value.
> 
> v[count] = next; //this sets the value inside the array
> count++;
> }
> *n = count;
> printf ("%d\n", count);
> }



Hahaha just mailed him the same code about 4 minutes before your reply, except it has a count--;


----------



## Troncoso

Haha. Yeah. He did end up doing that. Sorry if I sounded like an ass. I didn't mean to. I really do appreciate the help.


----------



## TrainTrackHack

> He didn't really, though. The next variable is set to the value read by fscanf. Then next is added to the array as an element. I don't see why I need a pointer for the next variable.


fscanf takes pointers to values, not values itself since otherwise it has no way of setting the values (C doesn't have C++ style references). You're passing the function an unitialised int, not it address, but since fscanf expects a pointer it dereferences the garbage value anyway which may point to any arbitrary memory location (possibly NULL if your compiler initialises primitives by default).

EDIT: Crap, just read the whole thread again, I assume the problem has been solved?


----------



## Troncoso

hackapelite said:


> fscanf takes pointers to values, not values itself since otherwise it has no way of setting the values (C doesn't have C++ style references). You're passing the function an unitialised int, not it address, but since fscanf expects a pointer it dereferences the garbage value anyway which may point to any arbitrary memory location (possibly NULL if your compiler initialises primitives by default).
> 
> EDIT: Crap, just read the whole thread again, I assume the problem has been solved?



Yeah it is. Thank you for explaining that, though. Even though I got it fixed, I didn't understand the solution.


----------



## Ankur

Hey guys I am thinking about mastering C and C++ this year. I have now 3 years of experience in C, C++ but I still think I need to learn a ton. What do you guys think, can you recommend me a good book?


----------



## Troncoso

Ankur said:


> Hey guys I am thinking about mastering C and C++ this year. I have now 3 years of experience in C, C++ but I still think I need to learn a ton. What do you guys think, can you recommend me a good book?



You should tell us what you know and if there are any aspects you know about but want to learn more of.


----------



## Ankur

I know all the fundamentals, basics, graphics in C basics, data structures, all the OOP concepts, quite much of inbuilt ASM. Just want to know a book where I can master these all.


----------



## mihir

Ankur said:


> I know all the fundamentals, basics, graphics in C basics, data structures, all the OOP concepts, quite much of inbuilt ASM. Just want to know a book where I can master these all.



You know OOPs concepts in C?
That is some advanced stuff. 
If you want to learn more stuff about OOPs in C 
http://www.planetpdf.com/codecuts/pdfs/ooc.pdf
And if you want to learn some more C syntax and concepts, try this book
http://ubuntuone.com/3fqhi1ftepRCXEfdKoXwEG
Kerninghan And Ritchie. The creators of C.


----------



## Troncoso

I'm having trouble with a simple structs assignment. I'm getting errors that I feel like should be getting. The first one is "undefined reference to 'createPerson" and it points to the main.c file. Here are all the files used.

main.c


		Code:
	

#include <stdio.h>
#include <stdlib.h>
#include "modifyPerson.h"

int main(int argc, char *argv[])
{
    char name[] = "Name";
    createPerson (name, 21, 180.0, 23, 2, 1991);

    return 0;
}


modifyPerson.h


		Code:
	

void createPerson(char *name, int age, float height, int day, int month, int year);

void printPerson();


modifyPerson.c


		Code:
	

#include <stdio.h>
#include <stdlib.h>
#include "person.h"

void createPerson(char *name, int age, float height, int day, int month, int year)
{
    Person newPerson = (Person) malloc (sizeof (Person));
    newPerson.name = name;
    newPerson.age = age;
    newPerson.height = height;
    newPerson.dob.day = day;
    newPerson.dob.month = month;
    newPerson.dob.year = year;

    return newPerson;
}

void printPerson(Person person)
{
    puts (person.name);
    printf ("%d\n%.2f\n", person.age);
    printf ("%d/%d/%d", person.dob.day, person.dob.month, person.dob.year);
}


person.h


		Code:
	

typedef struct {
    int day;
    int month;
    int year;
} DoB;

typedef struct {
    char name[20];
    float height;
    DoB birthDate;
} Person;



If I remove the function call from main, then it will compile just fine. But I need to run that method.


----------



## TrainTrackHack

How are you trying to compile it? The only things I can think of that could cause an undefined reference error are that for some reason either modifyPerson.c is not being compiled at all (did you remember to put it in the list of sources to compile?) or the object file is not being passed to the linker, so main.c compiles fine but the linker goes boinkers when it realises that you haven't actually provided the object file in which createPerson and printPerson are contained.

However, not sure if this is related to the undefined reference errors, but you're returning a value from the createPerson method which you've declared as a void. Also, you're trying to assign a pointer value into the struct - you'll either need to just get rid of the malloc (this seems like what you want to do and you can safely do this unless your assignment requires you to allocate memory dynamically) or change newPerson to a pointer type (declare it as a *newPerson rather than newPerson) and then change all you assignments to dereference the pointer (i.e. newPerson.name = name becomes newPerson->name = name).


----------



## Cromewell

Yeah that code is weird. Pretty much everything I've got is covered by hackapelite.

One thing though, what if I pass more than 20 characters in as a name?


----------



## Troncoso

The code is weird because I've been messing with it a lot just to get it to compile. The "createPerson" function is suppose to return a Person, which is a struct that is defined in person.h.

Though, I feel retarded now... when I was compiling I wasn't including the modifyPerson.c..... Hahaha.

Still, when I change modifyPerson.h to this (which is why I changed it to void):



		Code:
	

Person createPerson(char *name, int age, float height, int day, int month, int year);

void printPerson();


I get this error:

modifyPerson.h:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âcreatePersonâ



> However, not sure if this is related to the undefined reference errors, but you're returning a value from the createPerson method which you've declared as a void. Also, you're trying to assign a pointer value into the struct - you'll either need to just get rid of the malloc (this seems like what you want to do and you can safely do this unless your assignment requires you to allocate memory dynamically) or change newPerson to a pointer type (declare it as a *newPerson rather than newPerson) and then change all you assignments to dereference the pointer (i.e. newPerson.name = name becomes newPerson->name = name).



Also, could you explain that a little better? I feel this is the source to several of my other errors.



> One thing though, what if I pass more than 20 characters in as a name?



Haha. Yeah, I know. But for the assignment, he isn't requiring exception handling, because we are just focusing on structs.

And one last thing, am I including my headers the proper way? I get errors if I include a header in more than one place, but I'm not sure where to include them so they are properly linked.


----------



## TrainTrackHack

> Also, could you explain that a little better? I feel this is the source to several of my other errors.


Well first, functions defined as void do not return a value, but you already fixed that. The other point is the malloc. When you do 


		Code:
	

int i;
Person p;
type identifier;

insude a method, you automatically get the required storage allocated on the stack so you are free to use it as is. However, you're allocating memory on the heap using malloc, which returns a pointer to the new block of data - not only do you never use this storage or even free it, you're forcibly ramming the pointer value into the struct using a cast (most likely the first 4 or 8 bytes of the struct, that is the first characters of the name field, are set to seeminlg garbage values which you overwrite when you assign the values). The heap allocation here is useless - in general, every time you use malloc, you should be assigning the return value to a pointer (the identifier of which is prefixed by an asterisk). If you ever see something like 
	
	




		Code:
	

type identifier = malloc(num);

instead of


		Code:
	

type *identifier = malloc(num);

and you're positive that the identifier is not just a typedef for a pointer, alarm bells should be going off in your head. Just getting rid of the malloc (leaving you wuth just Person newPerson; ) should fix this.



> And one last thing, am I including my headers the proper way? I get errors if I include a header in more than one place, but I'm not sure where to include them so they are properly linked.


Did you remember to put in any include guards? All header files are generally wrapped in something like


		Code:
	

#ifndef HEADER_NAME_H_
#define HEADER_NAME_H_

/* all header contents go here */ 

#endif

to make sure that the header is processed only once even though it might be included in multiple files. What it simply does is check if the HEADER_NAME_H_ macro has been defined and if not, it defines it and includes everything up to the endif. The next time the same include file is encountered, the preprocessor sees that HEADER_NAME_H_ has already been defined, and simply skips everything up to the endif, ensuring that everything in the file gets included only once.

A quick question, by the way - have by any chance learned Java before C?


----------



## Troncoso

Thanks a lot for the help, mate. Keeping your words in mind, I was able to go back through my code and sort it out. All works as it should. Now my next assignment is to write an interpreter.....Hahaha.

And....yeah, I did. What gave it away?


----------



## TrainTrackHack

> And....yeah, I did. What gave it away?


A lot of Java programmers new to a language like C or C++ often forget that non-primitive types (objects and structs) don't always need to be allocated dynamically using new... seeing someone trying to dynamically allocate memory where unnecessary/wrong is almost dead giveaway of a programmer who started off using Java (or some other language with similar reference semantics, but it's almost always Java) ^^


----------



## Troncoso

hackapelite said:


> A lot of Java programmers new to a language like C or C++ often forget that non-primitive types (objects and structs) don't always need to be allocated dynamically using new... seeing someone trying to dynamically allocate memory where unnecessary/wrong is almost dead giveaway of a programmer who started off using Java (or some other language with similar reference semantics, but it's almost always Java) ^^



Haha. To be technical, I learned C++ before Java, but Java is my most prominent language. 

I have one more question though, involving function pointers:

I have this struct:


		Code:
	

typedef struct {
	void (*func)(instruction);
	union {
		double db;
		char ch;
	};
} instruction;


Within my source file, I have an array of these instructions. My question is, how would I loop through that array and execute each struct's function?

I thought I knew how to do this, but the fact that the instruction function has a parameter that is an instruction seems to cause problems. As such, this does not work:



		Code:
	

int i;
	for (i = 0; i <= instr_count; i++) {
		(*instr[i].func) (instr[i]);
}


instr being the array of instructions.

Running the code gives me this runtime error:

"Unhandled exception at 0x00000000 in Interpreter.exe: 0xC0000005: Access violation."


----------



## Cromewell

Instead of
(*instr_.func) (instr);
try
*(instr.func) (instr);

edit:
I'm guessing that it's getting confused on what to do, and hopefully changing the brackets will help. I try not to use structs and function pointers in general _


----------



## Troncoso

Cromewell said:


> I'm guessing that it's getting confused on what to do, and hopefully changing the brackets will help. I try not to use structs and function pointers in general



Haha. If that was an option, I'd definitely take that route. Not that C isn't a useful language, but again, given the option, I would not use it at all.


----------



## Cromewell

Troncoso said:


> Haha. If that was an option, I'd definitely take that route. Not that C isn't a useful language, but again, given the option, I would not use it at all.



I've been fighting with this off and on all day, I still can't get it to work. 

I'm going to keep trying but my god is it annoying.


----------



## Troncoso

Cromewell said:


> I've been fighting with this off and on all day, I still can't get it to work.
> 
> I'm going to keep trying but my god is it annoying.



Fighting with my problem, you mean? I can post the other code if that'd help.


----------



## Cromewell

I do mean your problem but I've got it now. I was thinking about what was wrong instead of working back from the error.

The gist of it is, you've made a pointer to a void function. But you haven't set that pointer equal to anything. This works as expected:


		Code:
	

void func(int instruct) {
     printf("Instruction: %d", instruct);
}

typedef struct {
    void (* func)();
    union {
        double db;
        char ch;
    };
} instruction;

int main() {
    instruction *ins = malloc(sizeof(instruction));
    
    ins->db = 2.5;
    ins->ch = 'a';
    ins->func = &func;
    
    printf("db: %f ch: %c",ins->db, ins->ch);
    ins->func(5);

    return 0;
}


----------



## TrainTrackHack

This probably has nothing to do with your error (I'm pretty sure Chromewell is on the right track there, it looks like the func isn't correctly initialised), but you pointer declaration in the struct is fishy.

Declaring it like this would be fine


		Code:
	

[B]struct instruction {[/B]
	void (*func)(instruction);
	union {
		double db;
		char ch;
	};
};

.since the type "instruction" is known from the first line onwards. But you've declared it like this


		Code:
	

typedef struct {
	[I]void (*func)(instruction);[/I]
	union {
		double db;
		char ch;
	};
[B]} instruction;[/B]

The name "instruction" isn't known until the last line, so when you declare the function pointer, the compiler doesn't actually know what "instruction" even is. It should at least give you a warning (I would have expected an error). In practice, what it really means in that when you do an actual function call, the compiler can't reliably check that you're passing it the correct arguments, so it will end up compiling fine but if you put in incompatible/wrong number of arguments you would most likely end up crashing the program. Of course, in your example you are passing the correct number and type of arguments, so I'm pretty sure that's not the root of your problem. In general, though, when you declare a struct using the latter (typedef) way, you're not supposed to use the name inside the struct.


----------



## Troncoso

Cromewell said:


> I do mean your problem but I've got it now. I was thinking about what was wrong instead of working back from the error.
> 
> The gist of it is, you've made a pointer to a void function. But you haven't set that pointer equal to anything. This works as expected:
> 
> 
> Code:
> 
> 
> void func(int instruct) {
> printf("Instruction: %d", instruct);
> }
> 
> typedef struct {
> void (* func)();
> union {
> double db;
> char ch;
> };
> } instruction;
> 
> int main() {
> instruction *ins = malloc(sizeof(instruction));
> 
> ins->db = 2.5;
> ins->ch = 'a';
> ins->func = &func;
> 
> printf("db: %f ch: %c",ins->db, ins->ch);
> ins->func(5);
> 
> return 0;
> }




This didn't turn out to be the issue at all. My problem was using the "strtok" function. It returned strange results and caused crazy exceptions. I don't know if this is in the code I posted, but I ended up initializing the instructions
with

instruction next = {0};

which works just fine. My only issue now, is that atof() won't convert strings to doubles...

I really appreciate all the help guys. Between you and hackapelite, you've given me several angles to look at my program with to help figure out whats wrong.


----------



## galerecon

Hey guys, I have a question. I have a program that I wrote last night and I'm trying to figure out how to calculate the sum for each player as well as the dealer. I was going to use an array called " int playersum[8];" but it won't let me pass an array through parameters. This way, each placing in the array will contain the total count for the game (I have 7 players and 1 dealer). 


		Code:
	

// main.cpp

#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <cstdlib>
#include <ctime>       //Headers
#include <string>
#include <iomanip>
using namespace std;
 
void PrintHeader();
void ShuffleDeck (int[]);
int GetCard(int[]);                //Function Prototype
char GetSuit(int);
void DealCard(int[]);

//This function will go to a specific location on the screen with (x,y) coordinants.
        void gotoxy(int x, int y)
        {
                HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );
       
           if ( INVALID_HANDLE_VALUE != hConsole )
              {
                    COORD pos = {x, y};
                        SetConsoleCursorPosition ( hConsole, pos );
                        }
       
         return;
        }

//This function will take the deck and add a number to it so it's not empty.
		void ShuffleDeck (int deck[])
		{
		   int temp = 0, n = 0;
 
			for (int i = 0; i < 52; i++)
		          deck[i] = i;
 
		   return;
		}

//This function will return the suit picture of the card when called.     
        char getsuit(int SuitNum)
        {
                switch(SuitNum)
                {
                        case 1: return char(3);
                        case 2: return char(4);
                        case 3: return char(5);
                        case 4: return char(6);
                }
        }

//Main function
int main()
{
        int y, z;
        //int PlayerSum[8]; <-- I need to figure out how to keep count of the sum for each player and dealer.
	int deck[52],
        char HorS;
        bool test[7];
        srand(time(NULL));     // Variable Declarations
 
        PrintHeader();          // Print the "BlackJack" header.
        ShuffleDeck(deck);      // Gives each card a value so the array is not just empty.
        DealCard(deck);         // Deals two cards for each person but doesn't show 1 card for the dealer.

// This for loop will set each value for test[] array == 'true'. 
        for(int i = 0; i < 8; i++)
        {
                test[i] = true;
        }
 
//Checks if Player 1 wants to hit or stay
		z = 16;
		y = 8;

        while(test[1] == true)
        {
		gotoxy(0,z);
		cout << "Player 1: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(9,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(11,y);
                                    cout << "XX";
				    z++;
                                    test[1] = false;       
                                }
        }
 
//Checks if Player 2 wants to hit or stay
		y = 8;

        while(test[2] == true)
        {
		gotoxy(0,z);
		cout << "Player 2: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(19,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(21,y);
                                    cout << "XX";
				    z++;
                                    test[2] = false;       
                                }
        }
//Checks if Player 3 wants to hit or stay
		y = 8;

        while(test[3] == true)
        {
		gotoxy(0,z);
		cout << "Player 3: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(29,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(31,y);
                                    cout << "XX";
				    z++;
                                    test[3] = false;       
                                }
        }
//Checks if Player 4 wants to hit or stay
		y = 8;

        while(test[4] == true)
        {
		gotoxy(0,z);
		cout << "Player 4: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(39,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(41,y);
                                    cout << "XX";
				    z++;
                                    test[4] = false;       
                                }
        }
//Checks if Player 5 wants to hit or stay
		y = 8;

        while(test[5] == true)
        {
		gotoxy(0,z);
		cout << "Player 5: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(49,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(51,y);
                                    cout << "XX";
				    z++;
                                    test[5] = false;       
                                }
        }
//Checks if Player 6 wants to hit or stay
		y = 8;

        while(test[6] == true)
        {
		gotoxy(0,z);
		cout << "Player 6: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(59,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(61,y);
                                    cout << "XX";
				    z++;
                                    test[6] = false;       
                                }
        }
//Checks if Player 7 wants to hit or stay
		y = 8;

        while(test[7] == true)
        {
		gotoxy(0,z);
		cout << "Player 7: Hit(h) or Stay(s)? ";
                cin >> HorS;
		cout << endl;
                        if(tolower(HorS) == 'h')
                                {
				    gotoxy(69,y);
                                    GetCard(deck);
                                    y++;
				    z++;
                                }
                                else if(tolower(HorS) == 's')
                                {
				    gotoxy(71,y);
                                    cout << "XX";
				    z++;
                                    test[7] = false;       
                                }
        }
//Dealer reveals card and hits if < 17 or stays if > 17.
		gotoxy(0,z);
		cout << endl << "Dealer reveals second card.";
		
		gotoxy(0,6);
		GetCard(deck);

		getchar();
        getchar();
        return 0;
}
 
void PrintHeader()
{
        cout << "============================================================================" << endl
                 << "|                             "
                 << char(3) << " " << char(4) << " BlackJack " << char(5) << " " << char(6)
                 << "                            |" << endl
                 << "============================================================================" << endl << endl;
 
        cout << "Dealer  Player 1  Player 2  Player 3  Player 4  Player 5  Player 6  Player 7" << endl
                 << "------  --------  --------  --------  --------  --------  --------  --------" << endl;
 
        return;
}
 
int GetCard(int deck[])
{
        bool test = true;
        char suit;
        int CardNum, value;
 
        CardNum = rand() % 52;    // Gets a random number from 52 (deck).
 
        while(test == true)       // The while loop will make sure no cards are repeated.
        {
                if (deck[CardNum] == -1)
                        CardNum = rand() % 52;
                else
                {
                    value = deck[CardNum] %13;
                    test = false;
                }
        }
 
        deck[CardNum] = -1;
 
        if (value == 0)  
		{
			cout << setw(3) << "A";
			//sum += 1;
		}
        else if (value > 0 && value < 10)
		{
            		cout << setw(3) << (value + 1);
		}
        else if (value == 10)
		{
            		cout << setw(3) << "J";       //Prints out the value on the screen.
		}
        else if(value == 11)
		{
            		cout << setw(3) << "Q";
		}
        else if(value == 12)
		{
			cout << setw(3) << "K";
		}
 
        suit = GetSuit(CardNum);   // Gets the suit for the card.
        cout << suit;
 
        return value;
}

//Gets suit for the card.
char GetSuit(int CardNum)
{
        int value;
        char suit = 0;
 
        value = CardNum / 13;
 
        switch(value)
        {
                case 0: suit = char(3);
                        break;
                case 1: suit = char(4);
                        break;
                case 2: suit = char(5);
                        break;
                case 3: suit = char(6);
                        break;
        }
        return suit;
}

//Deals 2 cards for each person. Dealer only shows 1 card.
void DealCard(int deck[])
{ 
        gotoxy(0,6);
        cout << ">";
        gotoxy(0,7);   // Dealer
        GetCard(deck);
 
        gotoxy(9,6);
        GetCard(deck);  //Player 1
        gotoxy(9,7);
        GetCard(deck);
 
        gotoxy(19,6);
        GetCard(deck);  //Player2
        gotoxy(19,7);
        GetCard(deck);
 
        gotoxy(29,6);
        GetCard(deck);  //Player 3
        gotoxy(29,7);
        GetCard(deck);
 
        gotoxy(39,6);
        GetCard(deck);  //Player 4
        gotoxy(39,7);
        GetCard(deck);
 
        gotoxy(49,6);
        GetCard(deck);  //Player 5
        gotoxy(49,7);
        GetCard(deck);
 
        gotoxy(59,6);
        GetCard(deck);  //Player 6
        gotoxy(59,7);
        GetCard(deck);
 
        gotoxy(69,6);
        GetCard(deck);   // Player 7
        gotoxy(69,7);
        GetCard(deck);
       
        return;
}


I know it's a lot, but a lot of it is repeated over and over again. For example the function getcard and getsuit is called many times when a player hits or stays.

I just can't figure out how I can keep track of the sums (totals) for each player. 
(Ace is a 1 not 11 and I'm only using one deck).

I would really appreciate for the help!


----------



## Cromewell

Your functions work and the rest of the code seems to execute fine (I had to correct a , in your main that should be a ; but that's just a minor typo).

One thing about your functions, since arrays are passed as a pointer you should be passing the length of the array. What if you wanted more than a 52 card deck? You'd have to update lots of 52s in your code.

Ideally, you should be using a function to ask each player to hit or stay, its repeated an awful lot.

Also, since you're using C++ so you can simplify things by making objects and passing them around. i.e. a player object, a deck object, card object etc. This way, each player can have a hand object (or whatever) which consists of say an array of cards and some methods to figure out what you are allowed to do i.e. no more hitting once you've busted.


----------



## galerecon

Cromewell said:


> Your functions work and the rest of the code seems to execute fine (I had to correct a , in your main that should be a ; but that's just a minor typo).
> 
> One thing about your functions, since arrays are passed as a pointer you should be passing the length of the array. What if you wanted more than a 52 card deck? You'd have to update lots of 52s in your code.
> 
> Ideally, you should be using a function to ask each player to hit or stay, its repeated an awful lot.
> 
> Also, since you're using C++ so you can simplify things by making objects and passing them around. i.e. a player object, a deck object, card object etc. This way, each player can have a hand object (or whatever) which consists of say an array of cards and some methods to figure out what you are allowed to do i.e. no more hitting once you've busted.



The reason you found a , instead of ; is because I deleted a variable that was useless at this time when posting here.

Yes, this was the second time I was told that. When you say object you mean class for each right? The problem with that is that I don't fully understand classes. And I was writing this for my lab in my Computer Science 1 class. Our teacher is terrible so almost all of this is what I learned by myself over the past few weeks.

Do you have any suggestions for a way to count the sum using my code that I wrote? This lab is due today, but I will be rewriting this over winterbreak using classes and such. This code was also written at 12am-8am. (Welcome to college). Thanks for the help.


----------



## Cromewell

I figured the comma was something like that, it's not a big deal that stuff happens 

Yes I mean classes.

To make it work with what you have, you need to track the cards each person has. Right now, I'm not seeing anything that does that. You can use more arrays for now if you aren't comfortable enough with classes yet. For each hit/stay loop you'd need to push the drawn card value to the players array. Kind of ugly but it will work.


----------



## galerecon

Cromewell said:


> I figured the comma was something like that, it's not a big deal that stuff happens
> 
> Yes I mean classes.
> 
> To make it work with what you have, you need to track the cards each person has. Right now, I'm not seeing anything that does that. You can use more arrays for now if you aren't comfortable enough with classes yet. For each hit/stay loop you'd need to push the drawn card value to the players array. Kind of ugly but it will work.



Thanks i appreciate the help.


----------



## neilofbodom

Hi guys

I have a C problem. I need to write a program which asks the user to input information about customers (to keep it simple, just name, surname and address). After the user input, I need to write that data to a text file.

I got this so far: 

CreateCustomer()
{

	char name[30];
	char surname[30];
	char address[100];

	FILE *customers;


	printf("New Customer Page. \n");
	printf("Please enter the customer's name. \n");
	scanf("%s",name);

	printf("Please enter the customer's surname. \n");
	scanf("%s",surname);

	printf("Please enter the customer's address. \n");
	scanf("%s",address);

	customers = fopen("Customers.txt","w");
	fprintf(customers,"%s %s %s",name,surname,address);
	fclose(customers);


}

After running the program (i'm running on Ubuntu so I'm using the terminal to compile and run my programs), and entering some test data, this error comes up: Segmentation fault (core dumped).

Am i doing the writing correctly? If not, what is the problem? Keep in mind that I just started C at University a couple of months ago, and this stuff is still new to me.

Also, just because I am curious, what does that error mean?

Cheers!


----------



## Troncoso

A Segmentation Fault, as a basic explanation, is an error that is thrown when you try to access something in a way that you can't. Usually from using pointers in the wrong way.

I think the issue is the way you are trying to store the user input into the char pointers (the arrays). Try something like this:



		Code:
	

CreateCustomer()
{

char name[30];
char surname[30];
char address[100];

FILE *customers;

customers = fopen("Customers.txt","w");
fprintf(customers,"This is a test string");
fclose(customers);
}


If that works, than my assumption is correct. If you search for "read user input into char array" in Google, you'll find that most people use a method of grabbing each char individually, all the while checking for the EOF character.


----------



## TrainTrackHack

Don't know if this is causing the issue, but you're only supposed to use printf for formatted data. For strings without formatting, it's better to use puts.

Also, you could use a debugger or if that's a bit too much, just comment out the lines and uncomment them one by one to see which line is causing the issue.


----------



## Cromewell

I believe the problem is the use of scanf. You need to pass the address of the storage variable not the storage variable itself.

However array bounds might quickly become a problem if you are reading long strings


----------



## TrainTrackHack

> I believe the problem is the use of scanf. You need to pass the address of the storage variable not the storage variable itself.


I don't think that's it... they're arrays, so they're really just pointers to blocks of chars anyway (what scanf wants).


----------



## Troncoso

hackapelite said:


> I don't think that's it... they're arrays, so they're really just pointers to blocks of chars anyway (what scanf wants).



Yes. Doesn't an array variable act as a pointer if you use it without brackets? Or would you still need to de-reference it? C isn't my best language. Haha.


----------



## TrainTrackHack

> Doesn't an array variable act as a pointer if you use it without brackets?


Yes... not sure what you mean by brackets, though but when used by itself an array "variable" (it's really a constant) is a pointer to whatever type the array elements are.


----------



## Cromewell

Ah yes you are right, should be OK with the arrays. Is the seg fault when you press enter on some user input? Do you get the output file created?


----------



## neilofbodom

Ok guys, I manage to get it working. Don't really know what the problem was with the code i posted here but as soon as i added this short algorithm

if (customers == NULL) {
		printf("Could not open file \n");
		exit(0);
	}

it worked. It is simply a condition that if the pointer returns NULL it should print that there was an error. I found it in a book I own.

However, I do have another problem now. I am writing perfectly to the text file except for when the user is asked for the address. Due to the spaces between the words, the program is taking only the first word entered and ignoring the rest. 

Reasoning it out, it is like a space or '\0' is the end of line at which point the program stops reading.

How can I solve this? Is there a function which can ignore the '\0' and maybe take an enter key or '\n' as the end of line instead?

Any help would be appreciated!!

Thanks for your replies!

Cheers


----------



## Ankur

Use


		Code:
	

fgets (address, 100, stdin);

Here 100 is the max character that will be read in address.
you can also use gets(address), but use it only if you are not doing any big project.


----------



## neilofbodom

But wouldn't that be used to read from a text file? 

What i need is to ask the user to input his address and the program to store that address in a text file as it was input.


----------



## Ankur

neilofbodom said:


> But wouldn't that be used to read from a text file?
> 
> What i need is to ask the user to input his address and the program to store that address in a text file as it was input.


You can use fgets for both, getting input from user and from a file too.
The 3rd parameter "stdin" is used for getting input from the user.
If you want to get from the file then in the 3rd parameter you put the variable of the FILE datatype.


----------



## neilofbodom

Ankur said:


> You can use fgets for both, getting input from user and from a file too.
> The 3rd parameter "stdin" is used for getting input from the user.
> If you want to get from the file then in the 3rd parameter you put the variable of the FILE datatype.



Ah i see, ok. 
I tried it out but it is not working. This is my code:

CreateCustomer()
{

        char address[30];

        FILE *customers;

        printf("Please enter the customer's address. \n");
	fgets(address, 100, stdin);

        customers = fopen("Customers.dat","a");
	if (customers == NULL) {
		printf("Could not open file \n");
		exit(0);
	}
	fprintf(customers,"%s ",address);
	fclose(customers);
	return 0;

}


----------



## Ankur

Did you try using gets??


----------



## neilofbodom

Ankur said:


> Did you try using gets??



Yes I have but it is simply skipping that line of code. It just asks the user and does not wait for the input, it ends there.


----------



## Ankur

neilofbodom said:


> Yes I have but it is simply skipping that line of code. It just asks the user and does not wait for the input, it ends there.


If you have scanf before fgets then it will skip fgets.
Use fgets instead of scanf.


----------



## neilofbodom

Ankur said:


> If you have scanf before fgets then it will skip fgets.
> Use fgets instead of scanf.



no scanf, just using the fgets.


----------



## Ankur

neilofbodom said:


> no scanf, just using the fgets.


It should work, I will try personally and check the problem, basically fgets doesn't get skipped, it goes to that line of code and encounters a /n which directly returns from the function and goes to next line.
I will debug the code personally and tell you, till that time try using getchar(); before fgets and run.

EDIT:
I ran you code on my PC, works fine for me.
Just try closing your IDE and opening it again and run it.


----------



## neilofbodom

Ankur said:


> It should work, I will try personally and check the problem, basically fgets doesn't get skipped, it goes to that line of code and encounters a /n which directly returns from the function and goes to next line.
> I will debug the code personally and tell you, till that time try using getchar(); before fgets and run.
> 
> EDIT:
> I ran you code on my PC, works fine for me.
> Just try closing your IDE and opening it again and run it.



Awesome dude, it worked. Just had to tweak some things around. Could I ask you, how would you use the malloc? Also, how do you use dynamic memory allocation to load strings (probably as binary) into memory? I need to do this so that the user can have the option to edit an entry. I thought it would be best to load into memory, edit the entry and load it back to the text file.

Cheers!!


----------



## Cromewell

If you are using C++ use a String, it's just so much easier. http://www.cplusplus.com/reference/string/string/

Otherwise, using malloc can be a pain especially when using it to resize char arrays for input and you don't know how long the input might be.


----------



## Ankur

neilofbodom said:


> Awesome dude, it worked. Just had to tweak some things around. Could I ask you, how would you use the malloc? Also, how do you use dynamic memory allocation to load strings (probably as binary) into memory? I need to do this so that the user can have the option to edit an entry. I thought it would be best to load into memory, edit the entry and load it back to the text file.
> 
> Cheers!!


If you just want the user to edit the file then ask him what field to edit, take the input in a variable then just paste it to the file.


----------



## neilofbodom

Cromewell said:


> If you are using C++ use a String, it's just so much easier. http://www.cplusplus.com/reference/string/string/
> 
> Otherwise, using malloc can be a pain especially when using it to resize char arrays for input and you don't know how long the input might be.



Problem is, I am using C. 
To find out how long the input might be, couldn't I find the size of the string and create an array depending on that size?


----------



## neilofbodom

Ankur said:


> If you just want the user to edit the file then ask him what field to edit, take the input in a variable then just paste it to the file.



That's what I was thinking. But how would I paste the edited field in the file? How would I delete the content of the field and  paste the new data in the previous slot?


----------



## Ankur

neilofbodom said:


> That's what I was thinking. But how would I paste the edited field in the file? How would I delete the content of the field and  paste the new data in the previous slot?


What you can do is scan the file till the address section is reached, then the remaining characters in the file will need to be retrieved in a variable then after that you will have to append the edited field to the field, then after that append the variable data.
But this is what I am thinking, there are better ways I think.
Plus if you are doing this in large scale then use databases instead of files.


----------



## Cromewell

neilofbodom said:


> Problem is, I am using C.
> To find out how long the input might be, couldn't I find the size of the string and create an array depending on that size?



There's a couple ways to work around that then. Both are essentially the same. The gist of what you do is read part of your input at a time and use realloc to extend your input variable.

One way to do it is like this (originally from http://www.mkyong.com/c/how-to-handle-unknow-size-user-input-in-c/):


		Code:
	

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    unsigned int len_max = 128;
    unsigned int current_size = 0;
 
    char *pStr = malloc(len_max);
    current_size = len_max;
 
    printf("\nEnter a very very very long String value:");
 
    if(pStr != NULL)
    {
	int c = EOF;
	unsigned int i =0;
        //accept user input until hit enter or end of file
	while (( c = getchar() ) != '\n' && c != EOF)
	{
		pStr[i++]=(char)c;
 
		//if i reached maximize size then realloc size
		if(i == current_size)
		{
                        current_size = i+len_max;
			pStr = realloc(pStr, current_size);
		}
	}
 
	pStr[i] = '\0';
 
        printf("\nLong String value:%s \n\n",pStr);
        //free it 
	free(pStr);
	pStr = NULL;
 
 
    }
    return 0;
}

It reads a character at a time and increases the buffer size as needed.


----------



## Darren

Alright I'm in C++ at my school and I need to finish this program. Basically I have to translate to pig latin following these rules.

If the word begins with a vowel (except y) add -way to the end of the word.

If it doesn't begin with a vowel then add a dash to the end of the word then move the first letter to the end of the word until you hit a vowel as your first letter, then add ay to the end of the word. (ex chair would be air-chay).

If it doesn't have any vowels at all then just add -way to the end.


I'm using Visual Studio 2010 by the way.

This is what I have so far and as it stands it just adds -way to the end of whatever I try. Confused mainly as to how to remove the letters and put them at the end of the word following rule 2. 




		Code:
	

//Darren Jones

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

int main()
{
	string word = "";
	string pig1 = "";
	string pig2 = "";
	int novowels = 0;
	
	
	cout << "Please enter a word to be translated. (-1 to end) " << endl;
	getline(cin, word);

	 

	while (word != "-1")
	{

		for (int x = 0; x < word.length(); x += 1)
		{
			if (word.substr(x, 1) != "a" && word.substr(x, 1) != "e" && word.substr(x, 1) != "i" && word.substr(x, 1) != "o" && word.substr(x, 1) != "u")
			{
				novowels = 1;
				pig2 = "way";
				pig1 = word;
			}
		}
		if (novowels = 0)
		{

			if (word.substr(0, 1) == "a" || word.substr(0, 1) == "e" || word.substr(0, 1) == "i" || word.substr(0, 1) == "o" || word.substr(0, 1) == "u") 
			{
				pig2 = "way";
				pig1 = word;
			}
			else
			{
				for (int x = 0; x < word.length(); x += 1)
				{
					while (word.substr(x,1) != "a" || word.substr(x,1) != "e" || word.substr(x,1) != "i" || word.substr(x,1) != "o" || word.substr(x,1) != "u")
					{
						pig2 += word.substr(x,1);
						word.erase(x, 1);
						pig2 = word;
					}
					pig2 += "ay";
				}
			}
		}
		cout << "The word is " << pig1 << "-" << pig2 << endl;
		cout << "Please enter a word to be translated. (-1 to end) " << endl;
		getline(cin, word);
	}

	system("pause");
	return 0;
}


----------



## Troncoso

Denther said:


> If it doesn't have any vowels at all then just add -way to the end.



The English language doesn't typically have words without vowels. Haha.


Regardless, what you want to do is search the word for a vowel, and when it finds one, go back one index and create 2 substrings, one with the letters to move, and the other with the rest of the letters.

Then, you want to concatenate the beginning letters to the end of the other letters the same way you add "way" to the end of the words.

In C you use String.h for such manipulations. I don't know if it's different in C++.


----------



## Darren

Troncoso said:


> The English language doesn't typically have words without vowels. Haha.
> 
> 
> Regardless, what you want to do is search the word for a vowel, and when it finds one, go back one index and create 2 substrings, one with the letters to move, and the other with the rest of the letters.
> 
> Then, you want to concatenate the beginning letters to the end of the other letters the same way you add "way" to the end of the words.
> 
> In C you use String.h for such manipulations. I don't know if it's different in C++.



Yeah I know the no vowel thing is weird but it's part of it and she'll check it. I know what I have to do and I created two strings but still no matter what I do, it always just adds -way to the end of it. Really starting to get on my nerves.


----------



## Darren

This is what I ended up with after some help from a friend and it works now. This was a complete scrap of the last one and start afresh.




		Code:
	

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

int main()
{
	string word = "";
	string pig1 = "";
	string pig2 = "";
	int vowelfound = 0;
	int vowellocation = 0;

	cout << "Please enter a word to be translated (-1 to enter) ";
	getline(cin, word);

	while (word != "-1")
	{
		
		    vowellocation = 0;
			pig1 = word;
			pig2 = "-way";
			
			for (int x = 0; x < word.length(); x += 1)
			{
						
				if (vowellocation == 0)
				{
					if (word.substr(x, 1) == "a" || word.substr(x, 1) == "e" || word.substr(x, 1) == "i" || word.substr(x, 1) == "o" || word.substr(x, 1) == "u")
					{							
						vowellocation = x;
						break;
					}
				}
				else break;
			}
			
			if (vowellocation > 0)
			{
				pig2 = "-" + word.substr(0, vowellocation) + "ay";
				pig1 = word.substr(vowellocation);	
			}

		

		cout << "The word translated is " << pig1 << pig2 << endl;

		cout << "Please enter a word to be translated (-1 to enter) ";
		getline(cin, word);

	}

	system("pause");
	return 0;
}


----------



## Troncoso

Well, you have 3 cases, so what you need to do is grab the first letter:



> If first != vowel
> add -way
> Else
> Grab letters until first vowel
> Append letters to end
> Add -way



Even just doing it like this will cover the "no vowels" case, as the result is the same for words beginning with constants and works with no vowels.

I'm going over your code now. It's overly complicated.

EDIT: Just noticed your post. Did that fix your problem?


----------



## Darren

Yeah it did. The second one was much better. I was reading through my code and realized I could cut out almost half of it and still accomplish the same thing. I did get some help from a friend though but was able to figure it out. Thanks for the help. My issue was just confusing myself with various loops and ifs.


----------



## Darren

Back again with a presumably easy question. My loop only works the first time I run it. The program is supposed to search a sequential access file for names matching the code you entered. Everything works fine the first time I run it but every time after that it just prompts me for an employee code without displaying those that match it.

Contents of file.

F1#John James
P2#Mary Dapper
F2#Mary Jones
P1#Jeff Bride
F2#Joel Adkari
P2#Kristy Jacob
F1#June Joana
F1#Jacob Sueba
P2#Tammy Janes
F1#Charles Smith
P1#Bridget Hines
P2#Jerry Kramer
P1#John Adams
P2#William Smith
P1#Jenny Adair
F1#Connie Gray
F1#Chris Thomas
F1#Carl Angles
P2#Jenny Jonah
F1#Carol Verace
P1#Ann Jerame
P2#Kate Krumpet
F2#Janice Paulo
P1#Suman Cary
P1#Ann Patel

Code:



		Code:
	

//Darren Jones

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string Name = "";
string Last = "";
string InputId = "";
string Id = "";
ifstream inFile;

int main()
{

inFile.open("Advanced27.txt", ios::in);


 if(inFile.is_open())
 {
	cout << "Enter employee code, enter -1 to end: ";
	cin >> InputId;
	cin.ignore();

	while(InputId != "-1")
	{

		while(!inFile.eof())
		{
			getline(inFile, Id, '#'); 
			inFile>>Name;
			inFile.ignore();
			inFile>>Last;
			inFile.ignore();

			if(Id == InputId)
			{	
				cout << Name << " " << Last << endl;
			}
		}
		
		cout << "Enter employee code, enter -1 to end: ";
		cin >> InputId;
		cin.ignore();
  }

 }

 else 
 
 {
	cout<<"File not found."<<endl;
 }

 system ("pause");
 return 0;

}


----------



## TrainTrackHack

You never reset the file to read from the beginning; having gone through the list once, the file reaches EOF and since it remains there, the condition of the inner loop fails every time after the first.

(Hint: use seekg)


----------



## Darren

hackapelite said:


> You never reset the file to read from the beginning; having gone through the list once, the file reaches EOF and since it remains there, the condition of the inner loop fails every time after the first.
> 
> (Hint: use seekg)



I understand what you're saying but this has never been an issue before when doing similar things without using seekg (no idea what that even is actually).


----------



## TrainTrackHack

Well, then it's simply the fact that you've been doing similar things but not the exact same thing (I can't comment on exactly why your other programs have worked without seeing the code first). As for seekg, I'm assuming this is a homework problem so I'll leave it for you to look up, but you can use it to move the get pointer (the pointer used for reading the file) back to the start of the file.


----------



## Darren

Back once again. I'm doing practice problems for an upcoming programming competition and me and my friend are truly stumped.

Question:

Assume that the hands of the clock move continuously around the face. Given the hour and the minute and a desired angle in degrees (0-360) between the hands, determine the smallest time before that angle occurs between the hands. Note that hands do not always line up "on the minute". Inputs will be integer.

Examples

hour: 12
minute: 10
desired angle: 100
output in minutes : 7.4

hour: 5
minute: 5
desired angle: 30
output in minutes : 16.3

Thanks for any tips. 

I'm using Visual Studio 2010.




		Code:
	

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main()
{
	int hour = 0;
	int minute = 0; 
	int desired = 0;
	double angle = 0;
	double time = 0;

	cout << "Enter hour: ";
	cin >> hour;
	cout << "Enter minute: "; 
	cin >> minute;
	cout << "Enter a desired angle: ";
	cin >> desired;

	angle = (hour*30 + minute*.5)- minute*6;

	if (angle > 180)
	{
		angle  = angle -360;
	}

	if(angle < 0)
		angle = angle/-1;

	angle = desired - angle;
	time = angle/6 + ((minute/60));

	cout << "Time in minutes: " << time << endl;


	

	system("pause");
	return 0;
}


----------



## Troncoso

So....... what's your issue?


----------



## S.T.A.R.S.

Denther said:


> Back once again. I'm doing practice problems for an upcoming programming competition and me and my friend are truly stumped.
> 
> Question:
> 
> Assume that the hands of the clock move continuously around the face. Given the hour and the minute and a desired angle in degrees (0-360) between the hands, determine the smallest time before that angle occurs between the hands. Note that hands do not always line up "on the minute". Inputs will be integer.
> 
> Examples
> 
> hour: 12
> minute: 10
> desired angle: 100
> output in minutes : 7.4
> 
> hour: 5
> minute: 5
> desired angle: 30
> output in minutes : 16.3
> 
> Thanks for any tips.
> 
> I'm using Visual Studio 2010.
> 
> 
> 
> 
> Code:
> 
> 
> #include<iostream>
> #include<iomanip>
> #include<cmath>
> 
> using namespace std;
> 
> int main()
> {
> int hour = 0;
> int minute = 0;
> int desired = 0;
> double angle = 0;
> double time = 0;
> 
> cout << "Enter hour: ";
> cin >> hour;
> cout << "Enter minute: ";
> cin >> minute;
> cout << "Enter a desired angle: ";
> cin >> desired;
> 
> angle = (hour*30 + minute*.5)- minute*6;
> 
> if (angle > 180)
> {
> angle  = angle -360;
> }
> 
> if(angle < 0)
> angle = angle/-1;
> 
> angle = desired - angle;
> time = angle/6 + ((minute/60));
> 
> cout << "Time in minutes: " << time << endl;
> 
> 
> 
> 
> system("pause");
> return 0;
> }



Okay...so what's the problem actually?


----------



## Darren

S.T.A.R.S. said:


> Okay...so what's the problem actually?



Derp. 

It doesn't work. The value for example one is returned as 7.5 and the second is a negative decimal answer like -15.64 or something like that.


----------



## Troncoso

It looks like your code doesn't let the actual angle be greater than 180, which would mean you could never achieve an obtuse angle such as 270.
That's what this code suggests anyway:



		Code:
	

if (angle > 180)
    {
        angle  = angle -360;
    }


The question doesn't specify if the angle can be in either direction (one direction would normally be +/- or the angle would be < or > 180).


----------



## Darren

Yeah I noticed that too ^^. I removed that bit of code and all it did was make my first value return as like -35ish. I think you're right about that. But that doesn't change my problem with the two examples being wrong.


----------



## Troncoso

Well, my last point makes a big difference on how you'd do this. For instance, the second example:

hour: 5
minute: 5
desired angle: 30
output in minutes : 16.3

On the clock face, the minute hand is behind the hour hand by 122.5 degrees. So, for the purpose of that question, is this -122.5 or is it 237.5 degrees?

Edit: Regardless of all that, I think your error is due to not accounting for the fact that as the minute hand moves forward, so does the hour hand. You account for that in your initial angle calculation, but you leave that out when try to find the angle to move to get to the desired result.


----------



## Troncoso

This got me pretty close:



		Code:
	

float hour;
float minute; 
float desired;	    
double angle;
double time;

angle = (minute * 6) - ((hour * 30) + (minute * .5)) ;

// Java method
angle = Math.abs( angle );

 if (angle > 180)
    angle = 360 - angle;
	    
 if (angle > desired)
    angle -= desired;
else
    angle = desired - angle;

// The distance to move the hour hand
double ticks = angle / 6 * .5;

// The final position of the hour hand (in minutes)
double hours = (minute * hour) + (minute * .5) + ticks;

// The distance between the minutes hand and the hours hand
double tomove = desired / 6.0;

// The final position of the minutes hand	    
double minutes = hours - tomove;

// The minutes that it takes to get to these positions
time = (angle + (hours - minutes))/6;


The positions seem relatively right for the first example, but I get like 10.2. For the second example I get 16.25, so I'm assuming the example was rounded.


----------



## 0x47

Hello, How can I incorporate functions written in other languages when I am writing a program ?
example: I am writing using C and I want to write a function that will work fast so I wrote it in assembler, and now I need to somehow to load it in to my project.
Is there some file format I can compile it to that is recognised by all languages ?


----------



## Troncoso

You can inline assembly code in C using the asm() function. For example:



		Code:
	

asm("movl %ebx, %eax");


----------



## 0x47

didn't know that , but I meant something else.
bad example probably, If I want to use function I wrote in C while I am programming In C#?


----------



## Troncoso

I can only give specific answers based on the languages. It's different for each.

Java, for example, let's you call C using JNI or JNA.

Here's how you would use C in C#:
http://stackoverflow.com/questions/11425202/is-it-possible-to-call-a-c-function-from-c-net

As you can see, that is completely different that C in Java or ASM in C.


----------



## 0x47

I see, I thought its a different process.
I don't have any specific issue , just being curious.
thanks for your help.


----------



## SpriteMidr

Does anyone know if there is a better way to implement a linked list than this in C?



		Code:
	

#include <stdlib.h>
#include <stdio.h>

typedef struct Item {
  void *data;
  struct Item *next;
  struct Item *prev;
} LinkedList;

struct Item *getnext(struct Item *current) {
  return current->next;
}

struct Item *getprev(struct Item *current) {
  return current->prev;
}

struct Item *newitem(void *data) {
  struct Item *newmem = malloc(sizeof(struct Item));
  newmem->data = data;
  newmem->next = NULL;
  newmem->prev = NULL;

  return newmem;
}

void join(struct Item *currentlast,
    struct Item *newlast) {
  currentlast->next = newlast;
  newlast->prev = currentlast;
}

int main() {
  // Testing it works
  int item1 = 64;
  int item2 = 34;
  LinkedList *newObj = newitem(&item1);
  LinkedList *anotherObj = newitem(&item2);
  join(newObj, anotherObj);

  // make sure it works. Try accessing the
  // 34 value from the item holding 64
  printf("%d ", *(int*) newObj->data);
  printf("%d ", *(int*) newObj->next->data);
  printf("%d ", *(int*) newObj->next->prev->data);
  puts("Seems right");
}


----------



## Cromewell

Better how? It looks functional to me. Technically you don't need a previous pointer (current->next = current->next->next) but there are reasons you might want to use a previous.

Is there a reason you are using C and faking object oriented with a bunch of structs? Usually you'd see function pointers like this (shamelessly stolen from SO )


		Code:
	

struct foobarbaz{
    int one;
    int two;
    int three;
    int(*exampleMethod)(int,int);
};

int addTwoNumbers(int a,int b){
    return a+b;
}

int main()
{
    // Now, define an instance of our struct
    // and add some default values.
    struct foobarbaz fbb;
    fbb.one   =1;
    fbb.two   =2;
    fbb.three =3;

    // Now add a "method"
    fbb.exampleMethod = addTwoNumbers;

    // Try calling the method
    int test2 = fbb.exampleMethod(13,36);
    printf ("test2: %u \n",  test2);

    printf("\nDone\n");
    return0;
}


----------



## SpriteMidr

Cromewell said:


> Better how? It looks functional to me. Technically you don't need a previous pointer (current->next = current->next->next) but there are reasons you might want to use a previous.
> 
> Is there a reason you are using C and faking object oriented with a bunch of structs? Usually you'd see function pointers like this (shamelessly stolen from SO )
> 
> 
> Code:
> 
> 
> struct foobarbaz{
> int one;
> int two;
> int three;
> int(*exampleMethod)(int,int);
> };
> 
> int addTwoNumbers(int a,int b){
> return a+b;
> }
> 
> int main()
> {
> // Now, define an instance of our struct
> // and add some default values.
> struct foobarbaz fbb;
> fbb.one   =1;
> fbb.two   =2;
> fbb.three =3;
> 
> // Now add a "method"
> fbb.exampleMethod = addTwoNumbers;
> 
> // Try calling the method
> int test2 = fbb.exampleMethod(13,36);
> printf ("test2: %u \n",  test2);
> 
> printf("\nDone\n");
> return0;
> }



So THAT is how function pointers work! Nice one! Thanks


----------



## Cromewell

SpriteMidr said:


> So THAT is how function pointers work! Nice one! Thanks


Other than how you specify what's in them they actually work almost exactly how you'd expect them to. Which is kind of nice


----------

