• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

arit

Member
Is there an easy way to read in numbers from a text file? The problem I have is that some are double digit numbers i.e. '40 12 6 15'. Because 'number' is an int it only brings in one at a time. Is there a way to include everything in infile until I reach a space?

I've got code like this:

Code:
int number;
ifstream infile ("C:\\C++\\numberstxt");
	
	if(!infile)
		{
			cout << "Can't open numbers.txt";
			cin >> hold;
			return(-1);
		}
        infile >> number;

If ifstream is usable with fscanf sometrhing simple as
Code:
while (fscanf(fp,"%i", &targetBuffer++) != EOF)
might do it.

Though even in C there might be a more elegant solution.
 

mooooose

Member
I'm looking for a good book on SQL (or just databases) and .NET development for beginners. I'm a CS major who took no CS classes this year and I'm rusty. I'm good in Java, I've done a ton in MIPS assembly and a little C. Just looking to do a few little projects.
 

Seanbob11

Member
I'm looking for a good book on SQL (or just databases) and .NET development for beginners. I'm a CS major who took no CS classes this year and I'm rusty. I'm good in Java, I've done a ton in MIPS assembly and a little C. Just looking to do a few little projects.

You could go here. It's quite helpful.
 

BosSin

Member
I've gotten too rusty with my coding due to laziness and a hatred for my old job.
I think subscribing to this thread and helping people out with coding problems and such will be a good way to get back into the game.

edit: oh and I'm a Java guy by the way. Interfaces and <Generic Types> 4 lyf
 

caffeware

Banned
Code:
int number;
ifstream infile ("C:\\C++\\numberstxt");
	
	if(!infile)
		{
			cout << "Can't open numbers.txt";
			cin >> hold;
			return(-1);
		}
        infile >> number;

My take. :) This code pushes numbers into list in vector.

Code:
#include <iostream>
#include <cstdlib> //for atoi
#include <fstream>
#include <sstream>
#include <vector>

int main()
{

    std::vector<int> numbers;
    std::string line;
    std::ifstream file("example.txt");

    if (!file){
        std::cout << "File not found!" << std::endl;
        return 0;
    }

    getline(file, line);
    while (!file.fail()){

        //split string
        std::string part;
        std::stringstream ss(line);
        while (ss >> part){
            numbers.push_back( atoi(part.c_str()) ); //actual
        }

        getline(file, line);
    }

    file.close();

    //print numbers
    for (size_t i = 0; i < numbers.size(); ++i){
        std::cout << numbers[i] << std::endl;
    }

    return 0;
}
 

Milchjon

Member
Anyone have a better idea why counter variables are usually called "i"?

I've looked around for a bit and so far the most plausible answer seems to be that it originates from the sigma notation for sums in maths. Which only leads to to the question of why it's used there in the first place.
 

corn_fest

Member
Anyone have a better idea why counter variables are usually called "i"?

I've looked around for a bit and so far the most plausible answer seems to be that it originates from the sigma notation for sums in maths. Which only leads to to the question of why it's used there in the first place.

Huh, that would make sense, I suppose. I always figured it was just a shorthand for "iterator" that became standardized.
 

BosSin

Member
Anyone have a better idea why counter variables are usually called "i"?

I've looked around for a bit and so far the most plausible answer seems to be that it originates from the sigma notation for sums in maths. Which only leads to to the question of why it's used there in the first place.

I thought it was just a shorthand for "index"
 
Anyone have a better idea why counter variables are usually called "i"?

I've looked around for a bit and so far the most plausible answer seems to be that it originates from the sigma notation for sums in maths. Which only leads to to the question of why it's used there in the first place.
'i' stands for index or iterator.
 
Huh, that would make sense, I suppose. I always figured it was just a shorthand for "iterator" that became standardized.

I thought it was just a shorthand for "index"

i literally use idx. i avoid thinking of it as iterator since some languages have Iterator objects for stepping through containers and I might confuse myself.

I'll through a spanner in the works ;)

I've always thought it was i because it was generally an int and people are lazy.

if it's an int that i can't be bothered naming properly, and it's purpose is not to step through an array (or similar) but rather eg. to repeat some function with the int as a factor, then for me it's 'n', as in from 0..n
 

smiggyRT

Member
The normal List<T> class in C# has AddRange(IEnumerable) for adding one sequence to it. If you're determined to use LinkedList, your best options are:
1) Make an extension method on LinkedList for adding two of them together.
2) Use the IEnumerable extension method Concat and construct a new linked list from the result.

Thanks for that, finally got it implemented.

Another c# question, this time to do with Selection sorting.
Ive been given the following code:

Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace BookSortingEx
{
    class Book : IComparable<Book>
    {

        public string ISBN;
        public string Title;
        public string Author;

        public Book(string ISBN, string Title, String Author)
        {
            this.ISBN = ISBN;
            this.Title = Title;
            this.Author = Author;
        }
        
        public override string ToString()
        {
            return Title + " by " + Author + " ISBN: " + ISBN;
        }

        int IComparable<Book>.CompareTo(Book other)
        {
            return this.Title.CompareTo(other.Title);
        }

    }


}
Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace BookSortingEx
{
    class Program
    {

        static void swap<T>(ref T x, ref T y)
        {
          //swapcount++;
            T temp = x;
            x = y;
            y = temp;
        }

        [B]public void SelectionSort(???) 
        {
            
                
        }[/B]

        static void printArray(int[] a)
        {
            for (int i = 0; i < a.Length; i++)
            {
                Console.Write(a[i] + ",");
            }
            Console.WriteLine();
        }

        static bool IsInOrder<T>(T[] a) where T : IComparable
        {
            for (int i = 0; i < a.Length - 1; i++)
            {
                if (a[i].CompareTo(a[i + 1]) > 0)
                    return false;
            }
            return true;
        }

        static void Main(string[] args)
        {

            string[] array1 = { "Fred", "Zoe", "Angela", "Umbrella", "Ben" };
            string[] titles = {"Writing Solid Code",
                "Objects First","Programming Gems",
                "Head First Java","The C Programming Language",
                "Mythical Man Month","The Art of Programming",
                "Coding Complete","Design Patterns", 
                "Problem Solving in Java"};
            string[] authors ={ "Maguire", "Kolling", "Bentley", "Sierra", "Richie", "Brooks", "Knuth", "McConnal", "Gamma", "Weiss" };
            int[] isbns = { "948343", "849328493", "38948932", "394834342", "983492389", "84928334", "4839455", "21331322", "348923948", "43893284", "9483294", "9823943" };

            Book[] library = new Book[10];

            for (int i = 0; i < library.Length; i++)
            {
                library[i] = new Book(isbns[i], titles[i], authors[i]);
            }

            
[B]            SelectionSort(library);
[/B]
            foreach (Book book in library)
            {
                Console.WriteLine(" {0} ", book);
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

Basically I have to complete the SelectionSort method, having trouble though since I'm not 100 percent sure what it is I'm meant to be sorting. I assume I'm sorting the ISBN numbers but what argument does SelectionSort take for that to be possible?
 

usea

Member
Thanks for that, finally got it implemented.

Another c# question, this time to do with Selection sorting.
Ive been given the following code:

[...]

Basically I have to complete the SelectionSort method, having trouble though since I'm not 100 percent sure what it is I'm meant to be sorting. I assume I'm sorting the ISBN numbers but what argument does SelectionSort take for that to be possible?

SelectionSort is supposed to sort Book objects.

Notice this line of code in main:
Code:
SelectionSort(library);
SelectionSort is being passed the library variable, which is defined here:
Code:
Book[] library = new Book[10];
So immediately you know that SelectionSort should take 1 parameter, either of type Book[] or some interface that an array of book implements. These would primarily be IEnumerable<Book>, ICollection<Book> and IList<Book>

So really you could take any of those 4 parameter types. I'd recommend IList<Book> or Book[] since you can directly index them with the [] operator. You're probably meant to take a Book[] array.

SelectionSort is probably supposed to implement a selection sort, modifying the array that's passed in so that it's ordered correctly at the end. There seems to be a convenient method IsInOrder<T>( T[] ) that you can use to check if your sorting works correctly. If you pass it your book array (library) after sorting it, it will return true or false whether your SelectionSort implementation sorted it correctly.

As for the implementation of SelectionSort, notice that the Book class already implements the interface IComparable<Book>. This interface is used for comparing two objects. So, the way you compare 2 books to determine which one comes first is already implemented for you, in the Book's CompareTo method. Don't manually compare titles, ISBNs or whatever. This is already done for you in this method.

If you simply want to get the code compiling and iron out any other bugs first, make your SelectionSort code look like this:
Code:
public void SelectionSort(Book[] books)
{
    Array.Sort(books);
}

Then, once everything is working right, change the code to implement selection sort.

It might also be helpful to add this line in your main, so you can tell quickly if there's a problem with your implementation.
Code:
SelectionSort(library);
[b]Console.WriteLine("Sorted correctly?: " + IsInOrder(library));[/b]

foreach (Book book in library)
{
    Console.WriteLine(" {0} ", book);
}
Console.WriteLine();
Console.ReadKey();
 

arit

Member
Basically I have to complete the SelectionSort method, having trouble though since I'm not 100 percent sure what it is I'm meant to be sorting. I assume I'm sorting the ISBN numbers but what argument does SelectionSort take for that to be possible?

According to SelectionSort(library); you are sorting an array of the type Book (-> Book[] library = new Book[10];). A book implements the method CompareTo, so you are sorting by the result of currentBook.CompareTo(otherBook). What CompareTo actually looks at to get your result should not bother you, it could be the digit sum of the title converted to upper case and reversed and subtracted 159 or just the isbn (although in the current implementation it just looks at the title and uses String.CompareTo()).
 
Code:
        int IComparable<Book>.CompareTo(Book other)
        {
            return this.Title.CompareTo(other.Title);
        }
/snip

Basically I have to complete the SelectionSort method, having trouble though since I'm not 100 percent sure what it is I'm meant to be sorting. I assume I'm sorting the ISBN numbers but what argument does SelectionSort take for that to be possible?

that's your clue right there. selectionsort takes the list as an argument, the book objects 'know' their own compare method. test it out on a few and see what values you get, that should point you in the right direction.

edit: i'm so slow.
 

Bruiserk

Member
EDIT: Solved it. Removed source code because it takes up a lot of the page and I feel bad.

Anyone familiar with PHP, here is my problem. So, I have two files. A website.php file and a markers.php file. Using Google's PHP/MySQL tutorial for putting markers onto their Google Maps API, I can successfully load every marker in my database onto the map. Now here is what I want to do:

Each marker is associated with an id number, and each id number is associated with a CPC (community policing center) name. What I want the user to be able to do is select one of these CPC names from a dropdown menu, hit a submit button, and reload the map with only the markers pertaining to that CPC. The thing is, when I click the submit button the markers.php script does not receive the value of the dropdown menu (ie the index) and does not print any latitude/longitude data (supposed to be accessible via XML). Can anybody offer some advice?
 

Fiftyeight

Neo Member
Hey guys, so I'm in an introductory class to C and I'm stuck on a project.

The goal is to take a word, reverse it, and have the program compare the two and give you an output as to how many characters are out of place. For example

3 (inputs)
tab draw racecar

tab, bat = two characters out of place (the character 'a' is still in the same spot)
draw, ward = four characters out of place
racecar = zero characters out of place


I've used examples in class how to reverse a series of numbers, but I'm drawing a huge blank as to how to get the actual letters to reverse.

Code:
#include <stdio.h>
#define MAXLEN 50

int main() {

    int n,i;

    int values[MAXLEN];
    int reverse[MAXLEN];

  
    scanf("%d", &n);

    printf("Enter %d values: ", n);
    for(i=0; i<n; i++) {
        scanf("%d", &values[i]);
    }

    for(i=0; i<n; i++) {
        reverse[n-i-1] = values[i];
    }


    for(i=0; i<n; i++) {
        printf("%d ", reverse[i]);
    }
    printf("\n");

    return 0;
}
 

CrankyJay

Banned
Hey guys, so I'm in an introductory class to C and I'm stuck on a project.

The goal is to take a word, reverse it, and have the program compare the two and give you an output as to how many characters are out of place. For example

3 (inputs)
tab draw racecar

tab, bat = two characters out of place (the character 'a' is still in the same spot)
draw, ward = four characters out of place
racecar = zero characters out of place


I've used examples in class how to reverse a series of numbers, but I'm drawing a huge blank as to how to get the actual letters to reverse.

Code:
#include <stdio.h>
#define MAXLEN 50

int main() {

    int n,i;

    int values[MAXLEN];
    int reverse[MAXLEN];

  
    scanf("%d", &n);

    printf("Enter %d values: ", n);
    for(i=0; i<n; i++) {
        scanf("%d", &values[i]);
    }

    for(i=0; i<n; i++) {
        reverse[n-i-1] = values[i];
    }


    for(i=0; i<n; i++) {
        printf("%d ", reverse[i]);
    }
    printf("\n");

    return 0;
}

You'll need a for loop that runs in reverse and place those values in the reverse array...some pseudo code:

Code:
char originalWord[];
char reverseWord[];

int j = 0;

// this will reverse the string
for(int i = originalWord.Length; i >= 0; i--)
{
    reverseWord[j] = originalWord[i];
    j++;
}

// now compare the two arrays
int charsOutOfPlace = 0;

for(int h = 0; h < originalWord.Length; h++)
{
      if(originalWord[h] != reverseWord[h])
          charsOutOfPlace++;
}
 

hateradio

The Most Dangerous Yes Man
Anyone familiar with PHP, here is my problem. So, I have two files. A website.php file and a markers.php file. Using Google's PHP/MySQL tutorial for putting markers onto their Google Maps API, I can successfully load every marker in my database onto the map. Now here is what I want to do:
. . .
  1. (Suggestion) You don't need parseToXML, just use htmlspecialchars. Additionally, you can enter an array of characters instead of calling str_replace several times.
  2. (Suggestion) Although your $CPC array is text entered by you, it's important to use mysql_real_escape_string for your queries. This prevents someone potentially hijacking your site's DB.
  3. (Probable Solution) You're using single quotes around $index. It should be $CPC[$index].

Instead of using the stuff under "//recieve the latitude and longitude for each id number," you can use the array $lid, in a WHERE IN() query.

Code:
$result = mysql_query('SELECT * FROM Locations WHERE lid IN (' . implode(',', $lid) . ')';

This way you only send one query to get all of the locations with those IDs. Then use the while to push your results. An even better solution would be to use an INNER JOIN, but that may be a little too advanced.
 

V_Arnold

Member
I have a JavaScript question, if I may.

I have made quite a progress with our upcoming indie RPG's basic battle simulator. (HTML5, JQuery for keyboard presses)
(it really does not allow anything besides unit placements, going around on the grid with your selector and selecting units), which is waaaay more complicated than anything I have done before, excluding a similar combat "engine" written in XNA a few years ago.

Now, I understand that JavaScript and "this.*" is shaky territory if it invoked from something different than the owner of the function. So I have read about using the call/apply instead, but to be honest, I did not completely get what all that means - I am just not at that level, I guess?

Anyway, my workaround to any issues with "this" is this:
if I have an object that have a function, and if that function uses any data from that object, I just make the function take the object itself as the first argument:

within the Object:

this.anything = function(theObject, otherArgs)
{
//Code
//When accessing any data:
theObject.statXYZ = ... etc
}

Is this a bad habit to take on, would be learning 'apply' properly more efficient and safe, or should I just not worry about it at this point? :D
 
I have a JavaScript question, if I may.

I have made quite a progress with our upcoming indie RPG's basic battle simulator. (HTML5, JQuery for keyboard presses)
(it really does not allow anything besides unit placements, going around on the grid with your selector and selecting units), which is waaaay more complicated than anything I have done before, excluding a similar combat "engine" written in XNA a few years ago.

Now, I understand that JavaScript and "this.*" is shaky territory if it invoked from something different than the owner of the function. So I have read about using the call/apply instead, but to be honest, I did not completely get what all that means - I am just not at that level, I guess?

Anyway, my workaround to any issues with "this" is this:
if I have an object that have a function, and if that function uses any data from that object, I just make the function take the object itself as the first argument:

within the Object:

this.anything = function(theObject, otherArgs)
{
//Code
//When accessing any data:
theObject.statXYZ = ... etc
}

Is this a bad habit to take on, would be learning 'apply' properly more efficient and safe, or should I just not worry about it at this point? :D

While I don't think it's a bad practice per se, the problem probably originates in your coding style. If "this" is not behaving as it should is because you don't understand how it behaves and you are probably just passing functions around without understanding the repercussions. I'd recommend you try some coffee script if you wan't to try to build something more OOPish.
 

V_Arnold

Member
While I don't think it's a bad practice per se, the problem probably originates in your coding style. If "this" is not behaving as it should is because you don't understand how it behaves and you are probably just passing functions around without understanding the repercussions. I'd recommend you try some coffee script if you wan't to try to build something more OOPish.

Yeah, good point. I avoid coffee script because I want to learn and adapt to JS, not dodge it just because real OOP is something that I have more experience with.

Here is a very quick rundown of what I am doing:
1) A field object that contains functions for everything regarding combat
2) A selector object whose sole purpose is to pass down positions and confirmation data (my plan is for this to be manipulated with mobile touches/keyboard/mouse, currently only keyboard)
3) A unit object that contains everything that a unit has to do (lots of stats, etc) (units are within the field, selector is acting independently)

Everything has draw() and update() functions, and every single interaction will be done via "action()"-s, that spawn (Within the scope of the field!), has some startup, need to have some additional requirements (depending on the action types...for example, a move action only requires an unoccupied space that is within your unit's move range. An attack action requires an enemy unit within range, etc.), an animation phase, and a finish.

The way this is set up, there is really no reason to ever update units via their own functions, when my goal is to have all interactions done via a chain of actions and selections. (That way, the game is easily converted to replays, imho). So there is some cross-referencing this way, but I plan on rewriting the main code several times as I find out new, more efficient ways of doing it :D
 

Fiftyeight

Neo Member
You'll need a for loop that runs in reverse and place those values in the reverse array...some pseudo code:

Code:
char originalWord[];
char reverseWord[];

int j = 0;

// this will reverse the string
for(int i = originalWord.Length; i >= 0; i--)
{
    reverseWord[j] = originalWord[i];
    j++;
}

// now compare the two arrays
int charsOutOfPlace = 0;

for(int h = 0; h < originalWord.Length; h++)
{
      if(originalWord[h] != reverseWord[h])
          charsOutOfPlace++;
}

Yeah, it's loops in particular that I have a hard time wrapping my head around. The lines with "for(int i = originalWord.Length; i >= 0; i--)" always confuse me. And then trying to figure out what the letters themselves distinguish - h, i, j, etc.
 

CrankyJay

Banned
Yeah, it's loops in particular that I have a hard time wrapping my head around. The lines with "for(int i = originalWord.Length; i >= 0; i--)" always confuse me. And then trying to figure out what the letters themselves distinguish - h, i, j, etc.


Okay, let's break it down...

for(int i = originalWord.Length; i >= 0; i--)

int i = originalWord.Length ... ("i" is arbitrary, you can name it whatever you want)...you're setting this variable to the length of the array

i>=0 ... you want this loop to execute over and over while i is greater than or equal to 0

i-- ... decrement the i variable for each pass in the loop
 

Fiftyeight

Neo Member
Yeah, this project is blowing my mind. Not to blame him completely, but this is our instructor's first teaching job and he blows right through the material without really discussing the concepts behind them. "Here's a code to do this, here's your assignment where you must alter said code and introduce new elements we haven't gone over."

Not only do I have to make a program that reverses the words, but I also have to combine it with one that compares the reversals to the originals and prints out how many characters are out of place. Super stressed out at the moment.
 
Yeah, this project is blowing my mind. Not to blame him completely, but this is our instructor's first teaching job and he blows right through the material without really discussing the concepts behind them. "Here's a code to do this, here's your assignment where you must alter said code and introduce new elements we haven't gone over."

Not only do I have to make a program that reverses the words, but I also have to combine it with one that compares the reversals to the originals and prints out how many characters are out of place. Super stressed out at the moment.

sounds hard now, really it's only a handful of loops, so work on your understanding of loops. maybe it would make more sense to you if you replaced the name of i with index, because conceptually you are for example taking the letter from one string at the index position of string.length() and putting it into another string. in the second problem you would have two index positions, one for each string, and compare the values at those indexes. the for loops merely control the index position.
 

Mabef

Banned
I have a nooby c++ question about pointers. When you declare a pointer, you put an asterisk before the name. Do you have to type that asterisk every time you use the pointer from then on? Like...
Code:
int *potatoPointer;

potatoPointer = &potatoes; //or...
*potatoPointer = &potatoes;
I was told you only have to use the asterisk while declaring the pointer, but my compiler gets grumpy if I leave it out. It thinks I'm converting an int to *int. What's the deal?
 
New to the whole big company job interview process, but I've heard that apparently IBM takes 2-3 months to hire someone once they've applied for the position here.

Am I the only one that think this is way too long?

I have a nooby c++ question about pointers. When you declare a pointer, you put an asterisk before the name. Do you have to type that asterisk every time you use the pointer from then on? Like...
Code:
int *potatoPointer;

potatoPointer = &potatoes; //or...
*potatoPointer = &potatoes;
I was told you only have to use the asterisk while declaring the pointer, but my compiler gets grumpy if I leave it out. It thinks I'm converting an int to *int. What's the deal?

*potatoPointer means "what potatoPointer points to" (the value within the address that potatoPointer has)

potatoPointer is the address.

So potatoPointer = &potatoes should be the right thing.
*potatoPointer = &potatoes means that you want to assign the address of potatoes to the value that potatoPointer points to... (not what you want)
 

hateradio

The Most Dangerous Yes Man
I have a JavaScript question, if I may.

. . .

Now, I understand that JavaScript and "this.*" is shaky territory . . .

Anyway, my workaround to any issues with "this" is this:
if I have an object that have a function, and if that function uses any data from that object, I just make the function take the object itself as the first argument:
. . .

Is this a bad habit to take on, would be learning 'apply' properly more efficient and safe, or should I just not worry about it at this point?
That's fine, but you're actually doing the same thing that call and apply do.

Code:
// this is what you're basically doing

function MyClass ()
{
  this.id = 0;
}

// uses the first parameter for the object
MyClass.prototype.someMethod = function (self, param1)
{
  self.id = param1 * 100;
}

// just uses [I]this[/I]
MyClass.prototype.someMethod2 = function (param)
{
  this.id = param * 100;
}

a = new MyClass();
a.someMethod(a, 2);
console.log(a.id); // a.id is 200
a.someMethod2.call(a, 3);
// that previous line should just be the following when you're in the right context
// a.someMethod2(3);
console.log(a.id); // 300

You basically use call to differ the context ("this") as the first parameter; notice that it's functionName.call(objectThis, firstParam) vs functionName(objectThis, param). Call is a method of functions (and other objects/callables) to which you pass parameters for that function.

Apply works the same way, but the second argument is an array.

You should only use call/apply when it's really required to override the this within a method. It's typically avoidable.

Note that jQuery has a method called proxy that you can also use, especially for events, wherein "this" goes a bit haywire (since it references the element).


References
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

Note that bind only works on new browsers.
 

Raistlin

Post Count: 9999
You'll need a for loop that runs in reverse and place those values in the reverse array...some pseudo code:

Code:
char originalWord[];
char reverseWord[];

int j = 0;

// this will reverse the string
for(int i = originalWord.Length; i >= 0; i--)
{
    reverseWord[j] = originalWord[i];
    j++;
}

// now compare the two arrays
int charsOutOfPlace = 0;

for(int h = 0; h < originalWord.Length; h++)
{
      if(originalWord[h] != reverseWord[h])
          charsOutOfPlace++;
}
Use recursion ... you know you want to :p
 

Kalnos

Banned
I have a nooby c++ question about pointers. When you declare a pointer, you put an asterisk before the name. Do you have to type that asterisk every time you use the pointer from then on? Like...
Code:
int *potatoPointer;

potatoPointer = &potatoes; //or...
*potatoPointer = &potatoes;
I was told you only have to use the asterisk while declaring the pointer, but my compiler gets grumpy if I leave it out. It thinks I'm converting an int to *int. What's the deal?

print the following variable values out to the console:

potatoPointer
*potatoPointer

IIRC the first will print the memory address of what potatoPointer points to and the second will print the value of what potatoPointer points to. After declaring using the asterisk means you're 'dereferencing' the pointer and accessing what's being pointed at.
 

BreakyBoy

o_O @_@ O_o
print the following variable values out to the console:

potatoPointer
*potatoPointer

IIRC the first will print the memory address of what potatoPointer points to and the second will print the value of what potatoPointer points to. After declaring using the asterisk means you're 'dereferencing' the pointer and accessing what's being pointed at.

When I first learned about it ages ago, I managed to remember this by thinking of the asterisk as a reference/dereference toggle. Kind of like telling the compiler to push a light switch.


i.e.:
abcVariable = a value?
(toggle)
*abcVariable = memory address of the variable

and conversely

xyzPointer = memory address of a variable
(toggle)
*xyzPointer = value of the variable at the memory address


It's been a long time since I've worked heavily in C/C++, but IIRC it always worked for me.

Edit: See the correction below.
 
When I first learned about it ages ago, I managed to remember this by thinking of the asterisk as a reference/dereference toggle. Kind of like telling the compiler to push a light switch.


i.e.:
abcVariable = a value?
(toggle)
*abcVariable = memory address of the variable

and conversely

xyzPointer = memory address of a variable
(toggle)
*xyzPointer = value of the variable at the memory address


It's been a long time since I've worked heavily in C/C++, but IIRC it always worked for me.

yep getting a handle on de-referencing is maybe the bulk of peoples pointers headaches in my experience. well, that and free'ing them.

only for above you should have:

abcVariable = a value
&abcVariable = memory address of the variable

eg

void someFunction(int* pointerToAnInt) {...}

is called like so: someFunction(&myInt);

and conversely for returns, Int* returnAPointer() { return &myInt; }
 

Mabef

Banned
Thanks feedinghand, kalnos, breakyboy, appleby. This be hard.
After declaring using the asterisk means you're 'dereferencing' the pointer and accessing what's being pointed at.
I think this is what was tripping me up. The fact that the same symbol does two different but related things, depending on what's going on.

I'm still stuck as balls on my class assignment, but that's its own mess. I'm supposed to ask the user for an int which will determine the size of an int array. I then call a function to create the array, sending int size as a reference. The function creates and populates the array, then sends back a pointer to the array. It's all very confusing to me and seems overly complicated, but then again I don't know what I'm doing. Here's something similar to what I'm trying, I'm not allowed to mess with the function prototypes/descriptions:
Code:
int *createArray(int &size);
main()
{
    int size;
    
    cout << "Input a size: ";
    cin >> size;
    
    int* arrayptr = createArray(size);
    
    cout << "\nTest print: After!\n";
    for (int i=0; i < size; i++)
        cout << *(arrayptr+i) << " ";
    
}

int *createArray(int &size)
{
    int array[size];
    
    for (int i = 0; i < size; i++)
        array[i] = i+1;
    
    cout << "Test print: before!\n";
    for (int i=0; i < size; i++)
        cout << array[i];
    
    return &array[0];
}
After hours of fumbling around, I've gotten the size successfully sent to the function, and something resembling an array sent up. But when I try to print the array I get weird garbage, so something's not right.

EDIT: Heading to bed, I'll check in mañana
 

BreakyBoy

o_O @_@ O_o
yep getting a handle on de-referencing is maybe the bulk of peoples pointers headaches in my experience. well, that and free'ing them.

only for above you should have:

abcVariable = a value
&abcVariable = memory address of the variable

eg

void someFunction(int* pointerToAnInt) {...}

is called like so: someFunction(&myInt);

and conversely for returns, Int* returnAPointer() { return &myInt; }


Ah, you're right. Like I said, it's been ages since I've been neck deep in it, and I'll also make use of the "it's 4 AM and I should be in bed" excuse. I'll make an edit pointing to your correction, so there's no confusion.
 
Ah, you're right. Like I said, it's been ages since I've been neck deep in it, and I'll also make use of the "it's 4 AM and I should be in bed" excuse. I'll make an edit pointing to your correction, so there's no confusion.


haha no worries i'm there often enough myself.




Thanks feedinghand, kalnos, breakyboy, appleby. This be hard.

I think this is what was tripping me up. The fact that the same symbol does two different but related things, depending on what's going on.

I'm still stuck as balls on my class assignment, but that's its own mess. I'm supposed to ask the user for an int which will determine the size of an int array. I then call a function to create the array, sending int size as a reference. The function creates and populates the array, then sends back a pointer to the array. It's all very confusing to me and seems overly complicated, but then again I don't know what I'm doing. Here's something similar to what I'm trying, I'm not allowed to mess with the function prototypes/descriptions:
Code:
int *createArray(int &size);
main()
{
    int size;
    
    cout << "Input a size: ";
    cin >> size;
    
    int* arrayptr = createArray(size);
    
    cout << "nTest print: After!n";
    for (int i=0; i < size; i++)
        cout << *(arrayptr+i) << " ";
    
}

int *createArray(int &size)
{
    int array[size];
    
    for (int i = 0; i < size; i++)
        array[i] = i+1;
    
    cout << "Test print: before!n";
    for (int i=0; i < size; i++)
        cout << array[i];
    
    return &array[0];
}
After hours of fumbling around, I've gotten the size successfully sent to the function, and something resembling an array sent up. But when I try to print the array I get weird garbage, so something's not right.

EDIT: Heading to bed, I'll check in mañana

Ok this is a good one actually, what's going on is that the array is being created on the Stack, which is memory local to the function. Memory is set aside, populated with data, and then you're getting the address of a section of that memory and returning it to main.

Because it's the stack though, that data is not kept and now you have a pointer to memory that could have anything it. So what you want to do is create that array on the Heap, where it exists until the program ends or you explicitly free it.

In c++ the code
Code:
new int[size];
allocates a memory chunk of size (sizeof(integer) * size) on the heap and returns a pointer to the start of that memory. You can happily pass this back to main without worrying about corruption (or "function returns pointer to local variable" warnings, depending on your compiler)
 

CrankyJay

Banned
Yeah, this project is blowing my mind. Not to blame him completely, but this is our instructor's first teaching job and he blows right through the material without really discussing the concepts behind them. "Here's a code to do this, here's your assignment where you must alter said code and introduce new elements we haven't gone over."

Not only do I have to make a program that reverses the words, but I also have to combine it with one that compares the reversals to the originals and prints out how many characters are out of place. Super stressed out at the moment.

Mentally you need to compartmentalize the different requirements of the assignment and knock out one at a time.
 

arit

Member
Thanks feedinghand, kalnos, breakyboy, appleby. This be hard.

I think this is what was tripping me up. The fact that the same symbol does two different but related things, depending on what's going on.

What can make it easier is just changing position of the *
Code:
int *number;
to
Code:
int* number;
So you might have your int* "datatype" and your dereferencing *variable (might be incorrect technical terms). But then you have to watch out for multiple declarations in one line, since

Code:
int* number1, number2;
would create number1 as a pointer to an int, and number2 as an actual int.
Declaring two int* would have to be
Code:
int* numbe1, *number2;
or
Code:
int* number1;
int* number2;

But depending on courses you already have to declare one at a line.
 

Mangotron

Member
So either due to my own stupidity or a crappy professor, I'm really stuck on creating this program. Any help, or even pointing me towards relevant resources would be hugely appreciated.

This is the pseudocode for the program

Code:
prompt and get a phone number from the user
   check phone number to determine if it is valid
   if it is not valid, 
      you must determine which error occurred
      (errors must be detected in the following order;
      (in case of multiple errors, only the FIRST error
      (is displayed and dealt with
      POSSIBLE ERRORS
       *    check first if length is not 8 or 11
       *    then check if first character not a 1
       *    last check if number is not all digits 0-9
   if the call is a long distance call,
      format and display like 1-(234)-567-8901
   else the call is a local call,      
      format and display like 1-567-8901
   otherwise
      display the appropriate error message.

The program is supposed to have its functions outside of main(), so far I've got the number input working, but I'm struggling with getting the if/else for the errors (all I'm allowed to use) and the formatting to work at all. I don't have any example programs to work from, and the textbook doesn't address errors or inserting into strings specifically, so I'm kind of just guessing.

The phone number formatting (mine):
Code:
string formatNumber(string phoneNumber)
{
	string formatNumber;
	const string dash = "-";
	const string leftp = "(";
	const string rightp = ")";

		if (phoneNumber.length() == 8);
		phoneNumber.insert(1, dash);
		phoneNumber.insert(5, dash);
		
		if (phoneNumber.length() == 11);
		phoneNumber.insert(1, dash);
		phoneNumber.insert(2, leftp);
		phoneNumber.insert(6, rightp);
		phoneNumber.insert(7, dash);
		phoneNumber.insert(11, dash);

	return formatNumber;

}

This isn't working at all, I'm assuming I'm just taking the wrong approach considering the program runs.

Status codes(mine):

Code:
int isValid(int status, string phoneNumber)
{
	if (phoneNumber.length() != 8)
		status = 1;
	else if (phoneNumber.length() != 11)
		status = 1;
	{
		if(phoneNumber.at(0) != 1)
			status = 2;
	}
	
	
	return status;
}

Also isn't working, I'm pretty fuzzy on how the .length thing works, so idk if this is formatted right or not. Also not sure how to do the 0-9 check.
 

arit

Member
So either due to my own stupidity or a crappy professor, I'm really stuck on creating this program. Any help, or even pointing me towards relevant resources would be hugely appreciated.

Also isn't working, I'm pretty fuzzy on how the .length thing works, so idk if this is formatted right or not. Also not sure how to do the 0-9 check.

Curly brackets are your friend, even if it is a simple one-line command thereafter (I suppose the language supports it).

How length() works should be known after a quick look into the language's API. Assuming the used language supports direct access to single chars of the string a simple
Code:
for (i = 0; i<input.length; i++){
  if (input[i] != i){
    return true // as in correct
  }   
}
return false
should do it.
 
So yeah, just finished my first week at work (jr java developer, first gig out of college). Is it bad for me to be overwhelmed?

Coming in midway in the process and my brain is exploding trying to comprehend the source code with little to no documentation (uml diagrams? LOL). Doesn't help that I wasn't a CS major, with my major being more on the front end design side, also never really had much experience being a part of a massive project midway in. For better or worse I'm also the only jr guy (pretty sure most of the people there are older than my parents). Everyone is pretty busy this week due to release being next week, so not too much teaching this week. At least most of the staff is quite nice and pretty funny and aren't shy on using colorful language about upper management.

So yeah, first gig out of college.... tips? People aren't kidding that real life isn't like school :p
 

usea

Member
So yeah, just finished my first week at work (jr java developer, first gig out of college). Is it bad for me to be overwhelmed?

Coming in midway in the process and my brain is exploding trying to comprehend the source code with little to no documentation (uml diagrams? LOL). Doesn't help that I wasn't a CS major, with my major being more on the front end design side, also never really had much experience being a part of a massive project midway in. For better or worse I'm also the only jr guy (pretty sure most of the people there are older than my parents). Everyone is pretty busy this week due to release being next week, so not too much teaching this week. At least most of the staff is quite nice and pretty funny and aren't shy on using colorful language about upper management.

So yeah, first gig out of college.... tips? People aren't kidding that real life isn't like school :p
Congrats on surviving a week. My experience (almost 2 years ago now) was very different. Work was very similar to school for me (besides the languages being totally different)

It's definitely normal to overwhelmed jumping into a very large existing codebase. One technique that works well for some people is to implement an entire (simple) feature end-to-end. It may take some time, but it will teach you a ton about the system, their coding style, etc.

Of course, you'd probably need a little bit of help for that. You'd need to know what a reasonable feature is, what the system does already, how it works, maybe a brief description of the architecture so you can find things that are done indirectly.

How good are you at java? Can you look at code and understand what it's doing? What have you been tasked with so far?
 
Congrats on surviving a week. My experience (almost 2 years ago now) was very different. Work was very similar to school for me (besides the languages being totally different)

It's definitely normal to overwhelmed jumping into a very large existing codebase. One technique that works well for some people is to implement an entire (simple) feature end-to-end. It may take some time, but it will teach you a ton about the system, their coding style, etc.

Of course, you'd probably need a little bit of help for that. You'd need to know what a reasonable feature is, what the system does already, how it works, maybe a brief description of the architecture so you can find things that are done indirectly.

How good are you at java? Can you look at code and understand what it's doing? What have you been tasked with so far?


I'm ok with java with using it mostly in school, but have zero experience doing huge projects (school work was mostly doing stuff solo, or groups of 4). And the project is wireless home security... which is a bit different from designing websites and games in college lol. Haven't really gotten any task yet, with this week spent most of the time getting paperwork and 'new hire stuff' done. The code is all over the place is due to company A buying company B and are trying to ductape stuff together. So yeah fun stuff. Hopefully when stuff dies down a bit, people can be free for me to bombard with questions.

Doesn't help that this gig is a 3 month to perm thing. How do you show your worth in that little time when you don't know anything? Be open? Eager to learn type of thing?

Things will hopefully get better over time (They said stuff will take months to get).
 
Top Bottom