• 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.

C++ Help?

Status
Not open for further replies.

wolfmat

Confirmed Asshole
The idea behind the indexing is 0*offset, 1*offset and so forth, so it makes perfect sense if it's all about addresses.
If you're on a much higher level, like in Lua, it's sort of unnecessary to think about it that way, apart from for convention's sake, of course.
 

poweld

Member
Sapiens said:
Can anyone help me here.

I have no idea where to start. But I'm burned out. I have to take this program and edit it so that it has support for multiple queues.
I'm not sure what the restrictions are or how you're supposed to handle it, but you can make a new preprocessor variable NUMQUEUES set to the number of Queues you'd like to handle. Within RunSimulation create a "vector<Queue<int> > vQueues(NUMQUEUES)" in lieu of the original Queue. Immediately after the time for loop, create a for loop through the Queues:

Code:
for (vector<Queue<int> >::iterator iQueue = vQueues.begin(); iQueue != vQueues.end(); ++iQueue) 
{ ... }

The rest will remain pretty much the same, replacing the original references to "queue" with "*iQueue"
 

Zeppu

Member
Sapiens said:
Can anyone help me here.

I have no idea where to start. But I'm burned out. I have to take this program and edit it so that it has support for multiple queues.

Single threaded or multi threaded?

If it's single threaded then all you have to do is create a vector<> and pop a number of queues into it. Then have a nested for loop within your current for loop and check for every item within the vector.

Edit: Yep, as described above.
 
Grr, having some more trouble. So, I have those same .h and .cpp files.
In my ODEsolver.h file, in public I have

Code:
typedef vector< float > FloatVector;

And whenever I need to refer to it in ODEsolver.cpp I call

Code:
ODEsolver::FloatVector etc
and call whatever on it. The problem is that vector has a default constructor where you can enter in the capacity and fill it with a value which I can do in the .h file by

Code:
FloatVector fv = FloatVector(size, initValue);

The problem is whenever I try calling that in the source file it won't let me use that constructor. In fact, it doesn't even recognize FloatVector at all. If I mouse over it in Visual C++ it says typedef<error-type> which I have no idea what that means
 

poweld

Member
Zoramon089 said:
Grr, having some more trouble. So, I have those same .h and .cpp files.
In my ODEsolver.h file, in public I have

Code:
typedef vector< float > FloatVector;

And whenever I need to refer to it in ODEsolver.cpp I call

Code:
ODEsolver::FloatVector etc
and call whatever on it. The problem is that vector has a default constructor where you can enter in the capacity and fill it with a value which I can do in the .h file by

Code:
FloatVector fv = FloatVector(size, initValue);

The problem is whenever I try calling that in the source file it won't let me use that constructor. In fact, it doesn't even recognize FloatVector at all. If I mouse over it in Visual C++ it says typedef<error-type> which I have no idea what that means
I believe that your problem is that you're trying to use the typedef as if it were a static instance of an object (referring to it as ODEsolver::FloatVector) when a typedef cannot be made into a static since it cannot be made into an object instance.

Think of it more like a rule that you're creating within the scope of the class.
 

phalestine

aka iby.h
Code:
                string name;
		cout << "Enter Full Name: ";
		getline(cin, name);
		cout << endl << "Your Name: " <<  name << endl<< endl;

ok so lets say the input was entered as First Middle Last,

How would I have it print First M. Last or Last, First M. ? Any hints?
 

CrankyJay

Banned
phalestine said:
Code:
                string name;
		cout << "Enter Full Name: ";
		getline(cin, name);
		cout << endl << "Your Name: " <<  name << endl<< endl;

ok so lets say the input was entered as First Middle Last,

How would I have it print First M. Last or Last, First M. ? Any hints?


string[] splitName = name.split(' ');

printf("%s %c. %s, splitName[0], splitName[1].CharAt[0], splitName[2]); // First M. Last
printf("%s, %s %c, splitName[2], splitName[0], splitName[1].CharAt[0]);// Last, First M.
 

phalestine

aka iby.h
CrankyJay said:
string[] splitName = name.split(' ');

printf("%s %c. %s, splitName[0], splitName[1].CharAt[0], splitName[2]); // First M. Last
printf("%s, %s %c, splitName[2], splitName[0], splitName[1].CharAt[0]);// Last, First M.


still couldnt get it to work, I see what you're doing though you are looking for an empty space ' '. I was thinking of using "find(url)" but not sure how to do it exactly.
 

CrankyJay

Banned
phalestine said:
still couldnt get it to work, I see what you're doing though you are looking for an empty space ' '. I was thinking of using "find(url)" but not sure how to do it exactly.

One of the string libraries has a method in there called split which will let you specify a character, in this instance a space, to split a string by into an array of strings.

It may be <stdstring> or <stdstring.h>

or just <String>

or <stdio> ... haha, one of those.

Haven't done C++ in awhile but that should put your on the right path.
 

phalestine

aka iby.h
CrankyJay said:
One of the string libraries has a method in there called split which will let you specify a character, in this instance a space, to split a string by into an array of strings.

It may be <stdstring> or <stdstring.h>

or just <String>

or <stdio> ... haha, one of those.

Haven't done C++ in awhile but that should put your on the right path.


thanks for the guidance :)
 
phalestine said:
Code:
                string name;
		cout << "Enter Full Name: ";
		getline(cin, name);
		cout << endl << "Your Name: " <<  name << endl<< endl;

ok so lets say the input was entered as First Middle Last,

How would I have it print First M. Last or Last, First M. ? Any hints?
Here's how I would do it:
Code:
string first, middle, last;
	
cin>>first>>middle>>last;
cout<<endl<<"Your Name: "<<last<<", "<<first<<" "<<middle.substr(0, 1)<<"."<<endl;
 

Chichikov

Member
CrankyJay said:
One of the string libraries has a method in there called split which will let you specify a character, in this instance a space, to split a string by into an array of strings.

It may be <stdstring> or <stdstring.h>

or just <String>

or <stdio> ... haha, one of those.

Haven't done C++ in awhile but that should put your on the right path.
It's defined in <string>, but I'm pretty sure std::string doesn't have a split method.
You'll need to use find and substr.
 

phalestine

aka iby.h
CrayzeeCarl said:
Here's how I would do it:
Code:
string first, middle, last;
	
cin>>first>>middle>>last;
cout<<endl<<"Your Name: "<<last<<", "<<first<<" "<<middle.substr(0, 1)<<"."<<endl;


wish I could do that but we have to use function getline :)

Chichikov said:
It's defined in <string>, but I'm pretty sure std::string doesn't have a split method.
You'll need to use find and substr.

Yup I figured it out, I used find and substr ;)

Thanks for all the help
 

CrankyJay

Banned
Chichikov said:
It's defined in <string>, but I'm pretty sure std::string doesn't have a split method.
You'll need to use find and substr.

Ah okay. I'm deep into C# development these days so I'm spoiled by all of these wonderful convenience functions. :D
 

poweld

Member
Chichikov said:
It's defined in <string>, but I'm pretty sure std::string doesn't have a split method.
You'll need to use find and substr.
Actually, there is a split method for char*'s. The method "strtok" tokenizes a c string, thus allowing you to split it on the match of a substring (c string).

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Here is the sample code (cause I'm just too lazy :D ):
Code:
/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

Output:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
 

Ducarmel

Member
I got a problem I just cant figure this one out

Written Assignment 1 has two sections. Choose one question from Section A and one question from Section B, and submit both to complete Written Assignment 1.

Section A: Choose either question 1 or 2 in Section A.

1. Create a program to determine the largest number out of 15 numbers entered (numbers entered one at a time). This should be done in a function using this prototype:

double larger (double x, double y);
Make sure you use a for loop expression inside your function.

Enter 15 numbers
11 67 99 2 2 6 8 9 25 67 7 55 27 1 1
The largest number is 99
Hints:
* Read the first number of the data set. Because this is the only number read to this point, you may assume that it is the largest number so far and call it max.
* Read the second number and call it num. Now compare max and num, and store the larger number into max. Now max contains the larger of the first two numbers.
* Read the third number. Compare it with max and store the larger number into max.
* At this point, max contains the largest of the first three numbers. Read the next number, compare it with max, and store the larger into max.

Repeat this process for each remaining number in the data set using a for expression.


I first I don't know how I can get the for loop to take 15 inputs from the and I dont get max to return properly


Code:
#include <iostream>
using namespace std;
double larger (double x, double y)
{
    double tempmax;
    double max = 0;
    if (x > y)
        tempmax = x;
    else
        tempmax = y;
    if (tempmax > max)
            max = tempmax;
    return (max);
}
int main()
{
    double max;
    cout << "Enter 15 Numbers" << endl;
    for (int counter = 0; counter<8; counter++)
    {
        double x;
        double y;
        double tempmax;
        cin >> x;
        cin >> y;
        tempmax = larger (x,y);
    }
    cout << "The largest number is " << max << endl;
    return 0;
}





I get it to work without the prototype function I still have the for loop problem. I dont know if my professor will accept it though.


Code:
#include <iostream>

using namespace std;
double larger (double x, double y);

int main()
{

    double x;
    double y;
    double tempmax;
    double max = 0;
    cout << "Enter 16 Numbers" << endl;
    for (int counter = 0; counter<8; counter++)
    {
        cin >> x;
        cin >> y;
        if (x > y)
            tempmax = x;
        else
            tempmax = y;
        if (tempmax > max)
            max = tempmax;
    }
    cout << "The largest number is " << max << endl;
    return 0;
}


oh and this is due in less then two hours.
 

Toby

Member
double max;
cin>>max;
double temp;
for(int count=0;count<14;count++)
{
cin>>temp;
max=larger(max, temp);
}
Edit: oh, returning double. Max is a double then.
 

TheExodu5

Banned
You shouldn't have two inputs inside your for loop. Read one input before beginning the for loop.

edit: woops page was a little old. yeah toby's got it.
 

Ducarmel

Member
Toby said:
double max;
cin>>max;
double temp;
for(int count=0;count<14;count++)
{
cin>>temp;
max=larger(max, temp);
}
Edit: oh, returning double. Max is a double then.
thanks for the help you too TheExodu5, brained farted with the two inputs in the for loop
 

Toby

Member
I figure this is a good place to ask:
Would knowledge of Python/Perl, Java, and C#&.net be beneficial when looking for a job?
My CS outline only requires me to do one. I have a better opportunity to do C# and .net this semester, but I also know I want to do Java.
Should I spend the extra $ to learn all of them?
 

CrankyJay

Banned
Toby said:
I figure this is a good place to ask:
Would knowledge of Python/Perl, Java, and C#&.net be beneficial when looking for a job?
My CS outline only requires me to do one. I have a better opportunity to do C# and .net this semester, but I also know I want to do Java.
Should I spend the extra $ to learn all of them?

Can't speak for Java but with C# you should have no problem finding a job. These jobs are rising in demand. But you need to learn newer stuff in addition to C# to broaden your marketability. Stuff like SilverLight and WPF will take you more places.
 

ianp622

Member
Toby said:
I figure this is a good place to ask:
Would knowledge of Python/Perl, Java, and C#&.net be beneficial when looking for a job?
My CS outline only requires me to do one. I have a better opportunity to do C# and .net this semester, but I also know I want to do Java.
Should I spend the extra $ to learn all of them?
Once you learn a programming language, you shouldn't really need to spend any money to learn another one. You should be able to pick it up with books or online resources.

What kind of job are you looking for?
 

Toby

Member
I really don't know what job I want. When I graduate I will have a BS in IT and a BS in business.
I signed up for the Java class, but I guess if I had to learn it on my own java would be the easy, as I already know C++(syntax is very similar right?)
Are there some good books on python/java/C# that give you programming assignments to complete?
 

Xelinis

Junior Member
Toby said:
I figure this is a good place to ask:
Would knowledge of Python/Perl, Java, and C#&.net be beneficial when looking for a job?
My CS outline only requires me to do one. I have a better opportunity to do C# and .net this semester, but I also know I want to do Java.
Should I spend the extra $ to learn all of them?


You'll have an easier time finding a job with C#. It's syntax is very similar to Java so if you know one, the other will be easy to pick up.
 
ianp622 said:
Once you learn a programming language, you shouldn't really need to spend any money to learn another one. You should be able to pick it up with books or online resources.
I agree with this. If I were you, I would just stick with C# and focus on extending your knowledge into either database or web (or both).
Toby said:
Are there some good books on python/java/C# that give you programming assignments to complete?
This looks like a good C# book.

Chichikov said:
Pick one and stick with it.
Edit: Agree with this as well. It's better for you to be good enough at one language to actually build real-world applications than to have just experimented with several.
 

Chichikov

Member
Toby said:
I figure this is a good place to ask:
Would knowledge of Python/Perl, Java, and C#&.net be beneficial when looking for a job?
My CS outline only requires me to do one. I have a better opportunity to do C# and .net this semester, but I also know I want to do Java.
Should I spend the extra $ to learn all of them?
Pick one and stick with it.
Companies care mostly about real world experience anyway.
Also, out of curiosity, are these the only languages your school teaches?
 

Zoe

Member
If you're doing a BS in IT/Business and NOT in Computer Science, C#/.Net would be more beneficial. Try to learn SQL too.
 

sadaiyappan

Member
Pastebin.com is a good site to paste code, someone was asking about this in an earlier post.

I learned C++ on my own (with help from the net of course), pointers and data structures was not that hard, it eventually clicked. But I still haven't figured out function pointers and design patterns.

I was listening to this tech podcast and they went on and on about how memristers are going to fundamentally change the way computers work and are programmed for.
 
I HATE THIS LANGUAGE SO SO MUCH

So I have this bit of code

Code:
i=argNum+1;
char* part = argv[i];

while(strstr(part,".")==NULL)
{
strcat(part, "_");
i++;
strcat(part, argv[i]);		
}

Looping over a structure called argv, with argNum values. The values are:
title
01.txt

This is supposed to get all the parts of a filename to send to some other function to parse it. The eventual filename is supposed to be "title_01.txt".

Anyway, it ALWAYS skips argv[i+1] EVERY TIME. I tried printing cout << argv[i+1] << endl before the loop and it shows "01.txt" correctly but when I print cout << argv << endl right after the i++ line it's blank. WTF?!
 

Zoe

Member
Zoramon089 said:
Looping over a structure called argv, with argNum values. The values are:
title
01.txt

So let me make sure I understand this. You have an array of strings, argv = {"title", "01.txt"}. Is argNum equal to 1 or 2?
 
Zoe said:
So let me make sure I understand this. You have an array of strings, argv = {"title", "01.txt"}. Is argNum equal to 1 or 2?


NEVER MIND
The problem was this stupid Athena computer system...basically Linux sucks, copying from a pdf removed characters that shouldn't have, it screwed up the tokenization and made them separate indices instead of together...etc, just forget it. So pissed
 

Zoe

Member
So here's what it looks like as it's executed with those variables:

Code:
i=argNum+1;				// i = 0 + 1 = 1
char* part = argv[i];			// part = "title"

if (strstr(part,".")==NULL)		// "title" does not contain "." -- passes
{
strcat(part, "_");			// part = "title_"
i++;					// i = 1 + 1 = 2
strcat(part, argv[i]);			// part = "title_01.txt"
}

if (strstr(part,".")==NULL)		// "title_01.txt" contains "." -- fails
{}

What is the problem?

Edit: Oops, I see your edit.

Your usage of char* and concatenation isn't very safe though.
 

deadbeef

Member
Zoramon089 said:
NEVER MIND
The problem was this stupid Athena computer system...basically Linux sucks, copying from a pdf removed characters that shouldn't have, it screwed up the tokenization and made them separate indices instead of together...etc, just forget it. So pissed
Better get used to that :) 99% of the time everything will be broken, then you finally fix it, say "neat!", and then move on to something else that's broken, haha
 
deadbeef said:
Better get used to that :) 99% of the time everything will be broken, then you finally fix it, say "neat!", and then move on to something else that's broken, haha

Yeah, I'm already onto the next problem, random Seg Faults in an array that is already initialized. I tried asking someone and they said it might be a "random transient bug in the compiler" Really?!
 

deadbeef

Member
Zoramon089 said:
Yeah, I'm already onto the next problem, random Seg Faults in an array that is already initialized. I tried asking someone and they said it might be a "random transient bug in the compiler" Really?!
Haha compiler bug? Reeks of desperation :) Always blame yourself first. The computer gods will smite you for your hubris otherwise.
 
60_gig_PS3 said:
seg faults are not random you probably overran the array

Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*
 

deadbeef

Member
Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*
An array of pointers is what you want?
 

CrankyJay

Banned
Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*

What are you doing here? Making an array of objects?
 
Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*

try this:

int x = width * height;
theType *data = new theType[x];
theTypeObj *y = new theTypeObj(whatever args);
data[0] = y;
 

poweld

Member
Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*
Code:
#include <iostream>
using namespace std;

class TestClass {
public:
    TestClass() {}
    void soundOff() {
        static int n = 0;
        cout << "TestClass " << n << " reporting" << endl;
        ++n;
    }
};

int main(int argc, char** argv) {
    int k = 10;
    TestClass* pTest = new TestClass[k];
    for (int i = 0; i < k; ++i) {
        if (pTest) {
            pTest[i].soundOff();
            ++pTest;
        } else {
            cerr << "pTest == NULL";
            return -1;
        }
    }

    return 0;
}
Code:
./a.out 
TestClass 0 reporting
TestClass 1 reporting
TestClass 2 reporting
TestClass 3 reporting
TestClass 4 reporting
TestClass 5 reporting
TestClass 6 reporting
TestClass 7 reporting
TestClass 8 reporting
TestClass 9 reporting

Seems to work OK for me. I even tried with arithmetic in the new (i.e. k*2) and it still worked alright. Maybe share your actual source?
 

Chichikov

Member
Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*

Did you make sure the allocation succeeded (i.e. returned pointed isn't null)?
You might be getting out of memory there (which is quite possible if your width and/or height are large numbers).

The code looks fine otherwise, but you can't be sure without seeing the implementation of theType class.

wayward archer said:
try this:

int x = width * height;
theType *data = new theType[x];
theTypeObj *y = new theTypeObj(whatever args);
data[0] = y;
This will not compile.
data[0] is of type theTypeObj and y is a *theTypeObj.
 

Slavik81

Member
Chichikov said:
Did you make sure the allocation succeeded (i.e. returned pointed isn't null)?
You might be getting out of memory there (which is quite possible if your width and/or height are large numbers).
new will by default throw a std::badalloc exception on failure. It will never return null.

Unless you're using an old, non-compliant compiler or changed the default behavior.



Zoramon089 said:
Mmm, I dunno...I can't find anywhere I did.

Ok so the array is initialized like this
theType* data = new theType[width * height];

data[0] = theTypeObj;

SEG FAULT

And for some reason, just printing out a character over a for loop is getting some very strange output printed when it's done (./a4 is the command to run)

*** glibc detected *** ./a4: double free or corruption (!prev): 0x00000000010f3070 ***
*Random numbers and letters here*
This is too vague for me to help you with. Post real code.
 

Chichikov

Member
Slavik81 said:
new will by default throw a std::badalloc exception on failure. It will never return null.
That's true if -
a. he has structured exception handling enabled.
b. he uses std::new

Neither are known, at least not to me.

I don't have any other idea as to why this could fail (outside of bugs in the class theType itself).
 

Kccitystar

Member
OK, so I'm pretty stuck here.

There are a few things I am stuck with as I don't know how to code that well, and my professor has given me two problems to work on:

1) A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional .50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that calculates and prints the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday's receipts. The program should use the function calculateCharges to determine the charge for each customer.

2)Write program segments that accomplish each of the following:
a) Calculate the integer part of the quotient when integer A is divided by integer B.
b) Calculate the integer remainder when integer A is divided by integer B.
c) Use the program pieces developed in (a) and (b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is seperated by two spaces.


So many things to do and I don't know where to start. Fuck my life.

Can anybody help?
 

Ducarmel

Member
Dude at least come half way and show us what you got so far or attempted to get.

I'm taking c++ myself not up to where you are skimming forward in my textbook I see a similar question.
 
Status
Not open for further replies.
Top Bottom