Jump to content


Check out our Community Blogs

LogicKills

Member Since 25 May 2008
Offline Last Active May 23 2010 05:44 PM
-----

#387529 Read and echo integers until a condition is met, help!

Posted by LogicKills on 29 September 2008 - 07:02 PM

Here is an example:

//For CodeCall
// LogicKills
#include <iostream>


int main()
{
    int num1,num2,new1,new2;
    
    while(1)
    {
            
            std::cin >> num1 >> num2;
            int new1 = num1 > num2 ? num1 : num2;
            if(new1 == num1)
                    new2 = num2;
                    
            else if(new1 == num2)
                 new2 = num1;
                 if (new1 - new2 >= 10)
                    break;
            else
                continue;
                }
                return 0;
                }

  • 2


#382739 Strings (CrashCourse)

Posted by LogicKills on 16 September 2008 - 09:46 PM

Working With Strings
<br>

Before We Get Started:
Not only is C++ super efficient with numbers, it can also do quite a lot with strings. A string can be anything from "program" to "hello my name is Patrick and I am ..." . Get the idea? Lets start off with the first type I will be going over and these are 'cstrings', or C-Style strings. Lets take a look at some code and then we can tear it apart and see how it functions.
#include <iostream>

//  using namespace std;
// ^^^ Can use that instead of std::
int main()
{
    char myCstring[10] = "Hello"; // a C-Style string..
    
    std::cout << myCstring << std::endl;
    
    
    return 0;
}
     

Ok, lets analyze this code.
The only thing that should look unfamiliar is the line with: 'char myCstring...'.

This is where we are declaring our string. All the a cstring consists of is an array of type char, or characters. The special thing about cstrings are that the last character looks something like this '\0'. This would be the last character of all strings, it is rightfully named the 'null character'.
This 'null character' is used by various functions that need to be able to handle strings. For example cout << would read HELLO and stop at the null character.
Declaring a cstring like we did is called a string literal it includes the null character so you don't have to remember to put it. The tedious way to declare a string is: char test[13]={'H','e','l','l','o','\0'};
-_- ... Doesn't look to fun eh, so lets stick to string literals for now..

When we declare a cstring the size of the array is usually left blank. This is for saftey precautions really, and the reason why goes beyond the range of this article. If you would like to know more about that research buffer overflows. So the safe thing to do is to let the compiler say how much it needs by leaving the size blank: char test[ ] = "leave me blank";.

Things You Can Do With CStrings...

strlen() - Finds the strings length
sizeof() - Finds the strings size in bytes.

Lets mess with some code with these functions:
#include <iostream>
#include <cstring> // need this for those functions :]

// lets go ahead and declare the namespace globally

using namespace std;

int main()
{
    const int str_size = 20; // We use this for our array size
    char myName[str_size];
    
    cout << "Why don't you enter your first name: ";
    cin  >> myName;
    cout << "Did you know your name is " << strlen(myName) << " characters long? ";
    cout << "\n";
    cout << "Well if you did know that, I bet you didn't know it is " << sizeof(myName) << "bytes";
    cout << "\n";
   
    
    return 0;
}

Basically we just used those functions I mentioned earlier. Both of them take 'myName' as an argument. Say we wanted the user to input multiple lines of text consisting of multiple words.. Well cin >> won't cut it there.. Here is an example.

#include <iostream>
#include <cstring> // need this for those functions :]

// lets go ahead and declare the namespace globally

using namespace std;

int main()
{
    const int str_size = 20; // We use this for our array size
    char myName[str_size];
    char fvColor[str_size];
    
    cout << "Enter your first and last name: ";
    cin  >> myName;
    cout << "Enter your favorite color: ";
    cin  >> fvColor;
    cout << "It seems that " << fvColor << " is your favorite color, " << myName << endl;
  
    
    
    return 0;
}

Here is the input and output::

Enter your first and last name:

logic kills

Enter your favorite color:

green

It seems that kills is your favorite color logic

Meh.. not what we wanted..
To fix this use cin.getline(myName,str_size);
The reason this happened lies within the inner workings of 'cin'.
When enter text their isn't a null character key on your keyboard, well at least not on mine anyways. So it still needs a way to find the end of the string. The way it does this is by: whitespace, newlines, or tabs.

PART II -The String Class-

C++ includes a class called string, it is actually also a type. To use it you have to include the <string> header file in your programs, it is also part of the std namespace. I personally prefer, and this all should prefer the string class.
It is a lot safer and easier to work with, not to mention all the cool things it can do. Not that I am bagging on C programmers, C strings can do most of the things string types can, it just comes a little easier using a built in type rather than an array of char.

Lets look at some of the things the string class can do..
#include <iostream>
#include <string> //You guessed it..
    
using namespace std; // Lets go ahead and declare it globally again..

int main()
{
    string test;   // an empty string ready for input;
    string assnstr = "I am a string..."; // Declaring a string literal..


   //You can assign one string to another like this..
    test = assnstr;
    cout << test << endl;
    
    //find the length of the string 
    cout << test << " is " << test.size() << " characters long counting the space. \n";
   
   //You can append strings on strings...
   test += " fearrrr meee ";
   cout << test << endl;
    return 0;
}

Their is so much you can do with strings, I just wanted to give you a taste.

Note To Readers: All my code was compiled and ran on Slackware Linux , however it should compile on anything. Also, Windows users if your output flashes by too fast add some of these.. :
cin.ignore();
cin.get();

Hope everyone enjoyed..

Here is some code to play with:
#include <iostream>
#include <string> //You guessed it..
    
using namespace std; // Lets go ahead and declare it globally again..

int main()
{
    string word;
    
    cout << "Enter a word:";
    getline(cin,word);
    cout << " ";
    
    for (int i = word.size(); i >= 0; i--)
    cout << word[i];
    
    cin.ignore();
    cin.get();
    return 0;
}

/LogicKills/
  • 1


#376987 Pointers(CrashCourse)

Posted by LogicKills on 26 August 2008 - 05:56 PM

Pointers In C++ (Crash Course)


Before We Get Started:
First lets talk briefly about computer memory and how it's addressing works.
Just like your house, the computer has an address for every memory block.
However instead of 124 LeeT Haxz0r Street, it is in a hexadecimal format.
So it looks something like ~ 0x00000000. Lets look at an example..

#include <iostream>

int main()
{
	int myInt;
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	
	return 0;
}

Ok, lets analyze this code.
First we declare an variable of type int called 'myInt'.
Then we use 'std::cout <<' to print the address of the variable to the screen.
This is possible because of the little '&' symbol. This is called the address operator.
Okay let's compile this thing..

<Linux>
$ g++ example.cpp -o example
$
$./example
$The address of 'myInt' is: 0xbfcbfab0

_________

<Windows>
Dev C++..
[F9 Key]
note: If you are compiling and running on widows, and your window vanishes before you can see the output.. add one of these:
'cin.get();'
__________

Alright if you compiled and ran it successfully congrats, please note that the memory address will vary. Alright since you understand a little bit how addressing works lets move on to actual pointers.

__________

Okay, so now with that all out of the way what do 'pointers' actually do.
Well their name is actually the thing they do, they point.
What they do is point to another address, this could be the address of a variable or something a little more complex like a function (we won't cover that yet).
In the example above we found out the address of our int by using that handy little operator called the.... yep, you guessed it: The Address Operator!

Lets open up that program and actually use a pointer and not just print the address to the screen..
Get your IDE's ready!!

#include <iostream>

int main()
{
	int myInt;
	int* p_myInt = &myInt; // in this case p stands for pointer :p
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	std::cout << "The address of my pointer \'p_myINt\' is: "<< p_myInt << std::endl;
	return 0;
}

Alright compile and run that!
Again the address will vary!

So for my output I got:
The address of 'myInt' is: 0xbfe52570
The address of my pointer 'p_myINt' is: 0xbfe52570

Hah!! The addresses match, so we successfully used a pointer.
Alright, pretty cool eh?
Wouldn't it be cooler if you could actually see the value that is at that address?
Well it turns out you can :]

To do that we are going to use the '*' dereferencing operator!
We are going to edit that program again a minuscule amount, let's assign a value to myInt~
#include <iostream>

int main()
{
	int myInt = 6;
	int* p_myInt = &myInt; // in this case p stands for pointer :p
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	std::cout << "The address of my pointer \'p_myInt\' is: "<< (p_myInt) << std::endl;
	std::cout << "The VALUE of myInt is : " << (myInt) << std::endl;
	std::cout << "The VALUE of *p_myInt is : " << (*p_myInt) << std::endl;
	return 0;
}

Compile and run it

Here is my output~
The address of 'myInt' is: 0xbfb2810c
The address of my pointer 'p_myInt' is: 0xbfb2810c
The VALUE of myInt is : 6
The VALUE of *p_myInt is : 6

_________

So let's get some things straight p_myInt is a pointer the value it holds is an address.
However *p_myInt is an int, the value it holds is what ever the current value is at the address.


<DANGERS>
When you create a pointer, your computer allocates memory for the address, but not for the data that will be at the address..

Example:

long* myPointer;
*myPointer = 13373773773;

So yes myPointer is a pointer, however we have neglected to say where it points address wise.
So this can cause major problems.
ALWAYS INITIALIZE YOUR POINTERS~!


__________

Alright so now you know a good amount about what pointers are an how they work, my next tutorial will be what you can do with pointer's and when they come in handy!

I hope this threw some light on the shady subject of pointers!

Next to come:
Using pointers, using new and delete, and some other fun stuff!

/LogicKills/
  • 7


#356159 Getting Started (C Programming)

Posted by LogicKills on 26 May 2008 - 09:41 PM

This tutorial will bring light to the common question:
"How Do I Get Started?"
I will outline the basic concepts and what you need to start programming in the C language.

To start programming in C you need a tool called a compiler. What a compiler does is convert the source code written by the programmer (you) into something the computer can read, in this case an executable file (.exe). Depending on the platform you are going to program on their are various compilers. Another thing you want is an environment to program in, most Windows compilers are placed within an IDE so you don't have to worry. With Linux however you have choices, I use VI or Gedit with syntax highlighting, works fine for me.

Windows:
Dev-C++
Borland
DJGPP

Linux
gcc
g++

I will make the code in this tutorial work on Linux and Windows so no need to worry about compatibility issues.

Your First C Program
I know it is a tradition to start with "Hello World", however I have a better starter program. Don't worry if you don't know what the code means, I will dissect it later.

( I will be using Dev-C++ and Gedit as an example for opening new files in )


Step One:
Open a new source file.
(In Dev-C++: File ---> New ---> Source File || or CTRL + N)
(Same thing in Gedit)


//FirstProgram.c
#include <stdio.h>

int main(void)
{
    
    printf("Hello CodeCall");
    getchar();
    return(0);

}

Make sure you typed the code, and did not just copy and paste.
After typing the code save the file as "FirstProgram.c".
Next we need to compile the program I will show how to do this with Dev and then with gcc.

Dev-C++
Save: File ----> Save As || or CTRL + F12
Compile: Execute ----> Compile || or CTRL + F9
Run: Execute ----> Run || or CTRL + F10

-----
Gedit w/ GCC
Save: File ----> Save || or CTRL + S
Compile: gcc FirstProgram.c -o FirstProgram (note: In terminal in correct dir)
Run: ./ FirstProgram (note: In terminal in correct dir)

------

If your program compiled and ran, congratulations! You are an official C programmer! This make look too simple now, however rest assured all programmers started like this. Soon you will be on your way to writing low-level system drivers, and maybe some other fun system software :]
If your program did not compile and(or) run make sure everything was copied and exactly right. On linux make sure you were in the correct directory, to make sure try: the command "ls" and look for your program. Next lets tear apart this program and start learning some basic concepts of C.

------

The Dissect

We will dissect the program line by line.

//FirstProgram.c
This line is a comment, a comment is used for describing an aspect of your program, listing the license you used and(or) contact info, version info, or maybe just some quick notes to remember what a specific line does so you don't forget down the line. In this example, I used a comment to tell the the file name was. Remember, don't overdue the comments too many will do the exact opposite of what they are intended. Two types of comments are available.
The multi-line C style comment: /* Comment Goes Between These */
Or the C++ single line style comment: //This is a single line comment


#include <stdio.h>
This is an include file. This line basically tells your compiler to add the contents of it to your file when it is compiling. The include file (or more popularly named "Header File" ) is just one of many that are included with your compiler. All of these files normally have a .h extension and are stored in a different file away from your source code. stdio.h is one of the most basic of header files and is almost always needed. It stands for Standard Input Output. Many types of header files exist and they support many different functions. When you get good enough you can even make your own.


int main(void)
This is the main function, it is requirement in EVERY C program. The main functions always has to be called. Everything between the { and } make up the main body of the program.


{ and }
These are code braces, these make up code blocks. All you really need to know is that code that is between { and } executes together.


printf("Hello CodeCall");
printf() is the standard output function. It can display simple text messages, or even variables.In this example it outputs the text "Hello Codecall". The "\n" is a newline tab this is really for aesthetics. Notice that this function ends with a semicolon ";". Every statement in in a C program ends with a semicolon.

getchar();
getchar(); is a function that waits for user input. A common problem with console applications on the windows platform is they do exactly what they are told to, except they do it too fast. If you are on windows take this line out, compile and run and see what happens. Their are other uses for this function, however I just used it here to stop the program from executing to fast.

return(0);
This is a return statement. In this program it returns a value of 0. This means the main function ran as expected with out any errors. Return values are important in other areas. The best example would be user defined function, more on that in the next tutorial.

------

Well that is the the dissection of the program line by line. This tutorial is aimed at complete beginners, remember it was made just to get your feet wet, and give you a small taste of the C language. If I would have outlined fundamentals in this tutorial it would have been way too long. Instead I will be making tutorials on every concept of the C language. I hope this tutorial helped some, and again it was meant to be basic. Expect more tutorials soon :]

/*LogicKills*/
  • 0


#356066 How do you look like?

Posted by LogicKills on 26 May 2008 - 09:18 AM

I run my own servers for various things.
2 nix boxes for coding and surfing, a windows box for my games.
I paid for/built them all.
  • -1


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download