Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
functional
Feb 12, 2008

Cirrus_Alreia posted:

In C++ is there any way to do if(x[f][b] == int)?
I just need it to know if the place is an integer so that it can run through the statement.
Is there any way to do it?[google searches have led nowhere]

Maybe this will help you... in C (and by extension C++), if someone gives you a typeless pointer p to some data, there is no "built-in" way to know what kind of data it's pointing to. Nor do you know how much of it is there. Maybe it's an int, or a struct, or maybe it's just random data that happens to look like what you're expecting. The only way to know is to keep track of it yourself somehow. Either you parsed the data yourself and know what it is, or you have some corresponding data somewhere that represents the type, or whatever.

This is different from other languages you may be used to where the language keeps track of type for you (e.g, instanceof in Java). C doesn't keep track of type. At least not for arbitrary data. A lot of C is dedicated to keeping tabs on what kind of data you're taking about, for instance, you declare an int variable, and return an int from your functions, but if your application isn't typed in this manner there's no a priori way to know what you're dealing with.

functional fucked around with this message at 16:37 on Feb 23, 2009

Adbot
ADBOT LOVES YOU

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

edit: Bah, missed the pagebreak; functional has said it all already.

Vanadium posted:

Check the declaration of x, then.
Indeed, really, without the compile-time type information, C has no idea whether some address in memory is intended to be, say, the number 84, or the character 'T'. There's no equivilent to Java's "instanceof" in C.

What are you trying to do? It sounds like your design is rather awkward.

edit: Now, are you trying to do something like:
code:
   float list = [3.14f, 4.0f, 2.718f, -2.0f]
   for (i = 0; i < 4; ++i) {
      if (is_float_equivilent_to_an_integer(list[i]) {
         printf("%f is a floating point representation of an integer\n", list[i]);
      }
   }
which would print the 4.0 and the -2.0?

Dijkstracula fucked around with this message at 17:19 on Feb 23, 2009

mistermojo
Jul 3, 2004

mistermojo posted:

How do I strip an extension from a file in C?

For example, I have a file called "output/1.png". I can use basename to get it to "1.png". I want to remove the .png as well.

oops, I misunderstood the assignment, I'm supposed to add a string before the extension. How would I go about doing that?

eg: 1.png to 1_thumbs.png

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

mistermojo posted:

oops, I misunderstood the assignment, I'm supposed to add a string before the extension. How would I go about doing that?

eg: 1.png to 1_thumbs.png

Completely untested and blatantly ignoring preexisting functions:
code:
char *add_suffix( const char *suffix, const char *str ) {

  char *new_str = malloc( strlen( suffix ) + strlen( str ) + 1 );
  assert( new_str );

  char *ret = new_str;

  while ( *str && *str != '.' ) *(new_str++) = *(str++);
  while ( *suffix ) *(new_str++) = *(suffix++);
  while ( *str ) *(new_str++) = *(str++);
  *new_str = 0;

  return ret;

}

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

mistermojo posted:

oops, I misunderstood the assignment, I'm supposed to add a string before the extension. How would I go about doing that?

eg: 1.png to 1_thumbs.png

strtok() or strchr()/strrchr(), then make your new string probably with strncat(), then rename()

mistermojo
Jul 3, 2004

Hmm, I'm trying to do this with strtok(), here is my code:

code:
int main(){
char original[] = "test.png";
char * pointer;
pointer = strtok (original,".");
printf("%s\n", pointer);
}
	
output: test

which I can strcat() _thumbs to.

But how do I save/use the actual extension, so I strcat() _thumbs and strcat() the extension to get test_thumbs.png

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

mistermojo posted:

But how do I save/use the actual extension, so I strcat() _thumbs and strcat() the extension to get test_thumbs.png

The direct answer is that strtok is stateful; if you want successive tokens, you pass NULL as the first argument. This is why you should probably instead use strsep or, at the very least, strtok_r.

Chuu
Sep 11, 2004

Grimey Drawer
Given the following:

code:
int f(){...}
...
const int& x = f();
What exactly is going on behind the scenes when you do this? From googling around apparently this is safe in the sense that the return value of f() is guaranteed to have a lifetime equal to x, but where is this value being stored? Is the entire stack frame still alive? If the whole purpose of this is to avoid calling a very expensive copy constructor, is it futile?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

ISO/IEC 14882:2003 8.5.3 #5 posted:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
...
  • If the initializer expression is an rvalue, with T2 a class type, and “cv1 T1” is reference-compatible with “cv2 T2,” the reference is bound in one of the following ways (the choice is implementation-defined):
    • The reference is bound to the object represented by the rvalue (see 3.10) or to a sub-object within that object.
    • A temporary of type “cv1 T2” [sic] is created, and a constructor is called to copy the entire rvalue object into the temporary. The reference is bound to the temporary or to a sub-object within the temporary.
The constructor that would be used to make the copy shall be callable whether or not the copy is actually done. [Example:
code:
struct A { };
struct B : public A { } b;
extern B f();
const A& rca = f(); // Either bound to the A sub-object of the B rvalue,
                    // or the entire B object is copied and the reference
                    // is bound to the A sub-object of the copy
—end example]

Also, yes, doing that to avoid an expensive copy is extremely futile, given that nearly every C++ compiler supports Return Value Optimization.

Avenging Dentist fucked around with this message at 09:33 on Feb 24, 2009

functional
Feb 12, 2008

ShoulderDaemon posted:


code:
  char *new_str = malloc( strlen( suffix ) + strlen( str ) + 1 );

Somebody likes a lot of elbow room in their code

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
Does anyone know what I would want to take advantage of to block packets from a program, except only once in a while? Like, every 5 seconds drop the packets from a program? I'm curious as to if it is possible.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Ethereal might do something like that, but if you explained what you're trying to do, people could probably give you a better solution.

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum

Avenging Dentist posted:

Ethereal might do something like that, but if you explained what you're trying to do, people could probably give you a better solution.
I'm not trying to do anything in particular I'm just curious about how you could go about it within Windows. Just a learning type of thing.

POKEMAN SAM
Jul 8, 2004
If you can choose where (IP:Port) the program connects, you can write a simple pass-through proxy and drop the packets in there. Would take but 10 minutes work.

evildoer
Sep 6, 2006
I'm writing some code in C and I have a pointer issue. When I print the value in the node, it is incorrect. This is all the code that I think is relevant to the problem.

Definitions:

struct list_el
{
char val[100];
struct list_el * next;
};
typedef struct list_el item;

char input[100];

The actual assignment.

current = (item *)malloc(sizeof(item));
*current->val = *input;

shrughes
Oct 11, 2008

(call/cc call/cc)

evildoer posted:

code:
*current->val = *input;

Use CODE tags, you butt.

That line is equivalent to current->val[0] = input[0];; what do you expect to happen.

shrughes fucked around with this message at 05:52 on Feb 25, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

shrughes posted:

[icode]current->val[0] = input[0];[/icode];

Oh the irony

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
code:
memcpy(current->val, input, 100)
or use strncpy if you really want.

shrughes
Oct 11, 2008

(call/cc call/cc)

Avenging Dentist posted:

Oh the irony

I got owned :(

ehnus
Apr 16, 2003

Now you're thinking with portals!

rjmccall posted:

code:
memcpy(current->val, input, 100)
or use strncpy if you really want.

Only if you don't mind the operation terminating when it hits a zero.

agscala
Jul 12, 2008

Is there a way to make VS2008 highlight keywords like 'string' or names of user-defined classes in my code? As it is right now, it is the same color as my variable names, which I think is slightly confusing. I figure some of you experienced with VS may know.

Google tells me nothing, though I have a feeling it's probably a simple fix-- something like I need to do something more then just #include<string> or maybe there is an option I'm missing.

agscala fucked around with this message at 00:45 on Feb 26, 2009

avatar382
Oct 17, 2005
i fapped
In Java, I can have a reference to any Object by using type Object.

How can do the same in C++? That is, have some sort of pointer or reference that can reference an object of any class?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

agscala posted:

Is there a way to make VS2008 highlight keywords like 'string' or names of user-defined classes in my code? As it is right now, it is the same color as my variable names, which I think is slightly confusing. I figure some of you experienced with VS may know.

You can't. Also I don't see how that's really confusing. All the words in this post are the same color and it's still readable. (Visual Assist might do something like that, though.)

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

avatar382 posted:

In Java, I can have a reference to any Object by using type Object.

How can do the same in C++? That is, have some sort of pointer or reference that can reference an object of any class?

void*

agscala
Jul 12, 2008

Avenging Dentist posted:

You can't. Also I don't see how that's really confusing. All the words in this post are the same color and it's still readable. (Visual Assist might do something like that, though.)

Ah, I was browsing the web looking for some premade dark color presets for VS and quite a few people had it set up to do that. It must have been some really roundabout thing to set that up.

random screenshot I seen floating around:

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

agscala posted:

Ah, I was browsing the web looking for some premade dark color presets for VS and quite a few people had it set up to do that. It must have been some really roundabout thing to set that up.

random screenshot I seen floating around:


That's not C++.

agscala
Jul 12, 2008

Avenging Dentist posted:

That's not C++.

:doh: That's C#. I didn't realize that VS handles syntax highlighting differently for C++ and C#.

oh well.

avatar382
Oct 17, 2005
i fapped

Avenging Dentist posted:

void*

Thanks.

So I did some googling on void pointers, and apparently you need to cast them to some specific type before they can be de-referenced.

I saw some example code where this was done, it looked like this:


code:
void Print(void *pValue, Type eType)  
{  
    using namespace std;  
    switch (eType)  
    {  
        case INT:  
            cout << *static_cast<int*>(pValue) << endl;  
            break;  
        case FLOAT:  
            cout << *static_cast<float*>(pValue) << endl;  
            break;  
        case STRING:  
            cout << static_cast<char*>(pValue) << endl;  
            break;  
    }  
}  
My question now is: What exactly is the Type type?

If I have an object of class Foo referenced by a void pointer, can I do something like this:

code:
void Print(void *pValue, Type eType)  
{  
    using namespace std;  
    switch (eType)  
    {  
        case INT:  
            cout << *static_cast<int*>(pValue) << endl;  
            break;  
        case FLOAT:  
            cout << *static_cast<float*>(pValue) << endl;  
            break;  
        case Foo:  
            cout << static_cast<Foo*>(pValue) << endl;  
            break;  
    }  
}  

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
C++ has a totally different type system from what (it seems) you're familiar with. Objects don't have any intrinsic idea of type at runtime. Tell us what you're trying to do, and we can start from there.

Hughlander
May 11, 2005

A couple of years ago, I came across a library that would serialize certain C++ variables to a database. From a usability point of view what was cool about it was you just needed to define the variable wrapped in a template such as:

code:
class MyClass : public SQLSerializableClass
{
    SQLSerializableVariable<int> m_MyInt;
};
There may have been a macro that defined the start of the class as well, but I don't recall.

Logically how it would need to work is there would have to be a connection between the class and the contained member variables. I was thinking that a macro at the start of the class could have a marking pattern and then the constructor of the template class can scan backwards from the address of this until it finds the marker. Then do another pointer math to find the address of the containing class. Given that, I can then register the class and the variable with an object that can handle the serialization.

However, that seems kind of 'off' from how I'd think the API would have worked. I suppose that it could have been a two step system that I'm just misremembering, that you define the class with a template then in the constructor you reference the variable/initialize it's value there. But, I swear that step wasn't needed though it's probably what I'm going to go with if there isn't another way of handling it.

So I'm trying to brainstorm how else one could do it and I'm not coming up with anything.. I can't think of anyway to have a preprocessor macro pass the this pointer to the constructor of the templated class. I can't think of a way of having a class initialization list and the template definition being in the same macro. I don't know any common way for C++ to handle introspection. I know there wasn't a custom compile step that ran a 3rd party preprocessor on the code... (IE: No Open C++)

So does anyone have a clue as to how else to handle this?

Hughlander fucked around with this message at 11:27 on Feb 26, 2009

MarsMattel
May 25, 2001

God, I've heard about those cults Ted. People dressing up in black and saying Our Lord's going to come back and save us all.

agscala posted:

:doh: That's C#. I didn't realize that VS handles syntax highlighting differently for C++ and C#.

oh well.

You can create a text file with custom keywords to highlight called "usertype.dat" in the same folder as devenv.exe which will be used for the "User Keywords" in VS. Put each each string that you'd like highlighted on a separate line. The IDE reads this at startup, so you need to restart to add new words etc. It's not intelligent at all (it has no idea what the strings actually represent) but its decent enough if you're working with something that has a fairly static interface (e.g. mine has various STL and COM entries).

avatar382
Oct 17, 2005
i fapped

rjmccall posted:

C++ has a totally different type system from what (it seems) you're familiar with. Objects don't have any intrinsic idea of type at runtime. Tell us what you're trying to do, and we can start from there.

I am trying to implement a data structure, lets say a stack, that can hold any type of object -- so I can do things like this

Foo a();
Bar b();
MyStack s();

MyStack.push(a);
MyStack.push(b);

... some time later ...

Bar x = MyStack.pop();
Foo y = MyStack.pop();

You are right on the money, I haven't seen C++ in like 5 years, and then it was an undergraduate course I didn't really find useful. Since then it's been all Java and Ruby.

EDIT: I realize the STL has classes that can do this sort of thing, but I want to implement my data structures own to develop the C++-fu needed to implement the real part of my project -- an interpreter for a functional language for class. Lucky for me, it's got to be implemented in C++.

avatar382 fucked around with this message at 15:26 on Feb 26, 2009

shrughes
Oct 11, 2008

(call/cc call/cc)

avatar382 posted:

I am trying to implement a data structure, lets say a stack, that can hold any type of object

Define "any type of object." Do you really want any type of object, or do you just want some fixed set of object types?

Nuggan
Jul 17, 2006

Always rolling skulls.

avatar382 posted:

I am trying to implement a data structure, lets say a stack, that can hold any type of object -- so I can do things like this

If you want a data structure that can hold any type of object you can use templated classes:
http://en.wikipedia.org/wiki/Template_(programming)

This will let you create, as per your example, a stack which could hold foo or it could hold bar, but not foo and bar at the same time. If you wanted do both at the same time you could use void pointers, but I wouldnt recommend it. Instead I would create a templated structure to hold 1) your data and 2) an int(char, etc, whatever works for your project) that keeps track of what data type the data is. Then you build your stack to accept instances of that structure.

What is it you're planning to do with a stack that can hold anything?

Nuggan fucked around with this message at 17:16 on Feb 26, 2009

TSDK
Nov 24, 2003

I got a wooden uploading this one

avatar382 posted:

EDIT: I realize the STL has classes that can do this sort of thing, but I want to implement my data structures own to develop the C++-fu needed to implement the real part of my project -- an interpreter for a functional language for class. Lucky for me, it's got to be implemented in C++.
If you're wanting to code up something like this just as practice, then try looking into member function templates. With a bit of effort you could knock up a toy stack that would let you do this:
code:
MyStack stack;
stack.push( 1.0f );
stack.push( 10 );
stack.push( 3.0f );

float a = stack.pop<float>();
int b = stack.pop<int>();
int c = stack.pop<int>(); // Throws MyStack::InvalidPopType
That should at least give you practice with templates and/or overloading and introduce you to the type system a little more.

schnarf
Jun 1, 2002
I WIN.

avatar382 posted:

Thanks.

So I did some googling on void pointers, and apparently you need to cast them to some specific type before they can be de-referenced.

I saw some example code where this was done, it looked like this:


code:
void Print(void *pValue, Type eType)  
{  
    using namespace std;  
    switch (eType)  
    {  
        case INT:  
            cout << *static_cast<int*>(pValue) << endl;  
            break;  
        case FLOAT:  
            cout << *static_cast<float*>(pValue) << endl;  
            break;  
        case STRING:  
            cout << static_cast<char*>(pValue) << endl;  
            break;  
    }  
}  
My question now is: What exactly is the Type type?

If I have an object of class Foo referenced by a void pointer, can I do something like this:

code:
void Print(void *pValue, Type eType)  
{  
    using namespace std;  
    switch (eType)  
    {  
        case INT:  
            cout << *static_cast<int*>(pValue) << endl;  
            break;  
        case FLOAT:  
            cout << *static_cast<float*>(pValue) << endl;  
            break;  
        case Foo:  
            cout << static_cast<Foo*>(pValue) << endl;  
            break;  
    }  
}  
The Type type is an enumeration, and it's user created. It's basically a pretty integer. Somewhere else in the code they would have gone:
code:
enum Type {
INT, FLOAT, STRING
};
The better way to do what they've done is overloading:
code:
void Print(int *pValue)  
{
     cout << *pValue << endl;  
}  

void Print(float *pValue)  
{
     cout << *pValue << endl;  
}  
And so on.

weldon
Dec 22, 2006
I'm trying to implement a polynomial class in C++, and I keep getting errors saying my member function isn't allowed to access the private variables, and this occurs throughout the entire code in many different places. Any idea why?

A function with the error is listed below, along with a summarized error code.

code:
#include <iostream>
using namespace std;
class polynomial {
      public:
             polynomial ();
             polynomial (const polynomial & other);
             polynomial (int D);
             polynomial (int D, int * C);
             ~polynomial ();
             polynomial & operator = (const polynomial & other);
             polynomial operator + (const polynomial & other) const;
private:
              int d;
              int * c;
};
code:
//assignment operator
polynomial:: polynomial & operator = (const polynomial & other){
             delete[] c; //delete old array (to the left of = sign)
             c = new int[other.d + 1] ; //create new array = to the size of the one to the right of the = sign
        d = other.d; //sets new degree value to that of the new array
    for (int i =0 ; i <= other.d; i++){
        c[i] = other.c[i];
    }   
    return(this) ;
}
code:
`int polynomial::d' is private within this context  (same thing with c)

schnarf
Jun 1, 2002
I WIN.

weldon posted:

I'm trying to implement a polynomial class in C++, and I keep getting errors saying my member function isn't allowed to access the private variables, and this occurs throughout the entire code in many different places. Any idea why?

A function with the error is listed below, along with a summarized error code.

code:
#include <iostream>
using namespace std;
class polynomial {
      public:
             polynomial ();
             polynomial (const polynomial & other);
             polynomial (int D);
             polynomial (int D, int * C);
             ~polynomial ();
             polynomial & operator = (const polynomial & other);
             polynomial operator + (const polynomial & other) const;
private:
              int d;
              int * c;
};
code:
//assignment operator
polynomial:: polynomial & operator = (const polynomial & other){
             delete[] c; //delete old array (to the left of = sign)
             c = new int[other.d + 1] ; //create new array = to the size of the one to the right of the = sign
        d = other.d; //sets new degree value to that of the new array
    for (int i =0 ; i <= other.d; i++){
        c[i] = other.c[i];
    }   
    return(this) ;
}
code:
`int polynomial::d' is private within this context  (same thing with c)
You need to declare it
code:
polynomial:: polynomial & polynomial::operator = (const polynomial & other) {
Or just stick the whole cpp file in namespace polynomial and avoid the ugliness.

floWenoL
Oct 23, 2002

quote:

Or just stick the whole cpp file in namespace polynomial and avoid the ugliness.

There is no "namespace polynomial"; it's a class.

weldon posted:

code:
//assignment operator
polynomial:: polynomial & operator = (const polynomial & other){
             delete[] c; //delete old array (to the left of = sign)
             c = new int[other.d + 1] ; //create new array = to the size of the one to the right of the = sign
        d = other.d; //sets new degree value to that of the new array
    for (int i =0 ; i <= other.d; i++){
        c[i] = other.c[i];
    }   
    return(this) ;
}
code:
`int polynomial::d' is private within this context  (same thing with c)

You're declaring operator=() as a member function but your definition is for a non-member function. You want:

code:
//assignment operator
polynomial:: polynomial & polynomial::operator = (const polynomial & other){
Also you need to do "return *this;", and you probably want to make sure that &other != this, as otherwise you'd be accessing newly-deleted memory.

Adbot
ADBOT LOVES YOU

weldon
Dec 22, 2006

schnarf posted:

You need to declare it
code:
polynomial:: polynomial & polynomial::operator = (const polynomial & other) {
Or just stick the whole cpp file in namespace polynomial and avoid the ugliness.

Sorry first big class project ive done and im not too experienced, but I thought it was already declared? I thought that when it was called,
for instance
p1 = p3

that p1's private variables could be used just as (c , d) and p3 could be used as (other.c, other.d)?

I guess what Im trying to say Is i dont know how to declare it but still have it modify the values.

Thanks for the quick response by the way :)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply