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
Sapozhnik
Jan 2, 2005

Nap Ghost
Has anyone done anything serious with WTL, and if so do you have any comments on it? I've created a few noddy components/COM clients using ATL at work before, but I don't do much GUI stuff, so I'd like to give WTL a go for a project I'm working on in my spare time.

I'm not entirely sure how to go about structuring my code though, since Microsoft doesn't really seem to do the whole MVC thing, and Win32's window messaging system gives me migraines. The cleanest thing I can come up with at the moment is to use CContainedWindowT everywhere, write controller mixins that respond to each CContainedWindowT's messages, then multiple-inherit the whole thing into a big master class which dispatches to the mixins via a big set of alternative message maps. Is this going to cause problems further down the line?

I'd really like to use WTL though, simply because it has some very sexy and creative (ab)uses of C++, and it creates super-tight executables, which I love. Statically dispatched virtual function calls? Bring it on!

Adbot
ADBOT LOVES YOU

Glasgerion
Jul 25, 2007
Strike on strike on

Lexical Unit posted:

How you'd resize the window depends on a million factors.

Sorry, you're right that was a horrible question. I'm using ncurses, and I want to have more room to put things in than the 80 x 25 I get default in windows. I know there is the resizeterm function, but I read you can't use that unless a couple of environment vars aren't set. Is there a way around that?

EDIT: Nevermind, got it.

Glasgerion fucked around with this message at 06:09 on Apr 17, 2009

Vinterstum
Jul 30, 2003

huge sesh posted:

It's certainly not all the program's doing but it's really not that complicated. I don't allocate that much memory, page file is normal. std::vector works fine elsewhere in the program. I guess I'll look around for possible heap corruption. Just seems weird that it would happen every time.

The simpler your program is, the more predictable your memory layout is likely to be (and any corruption to have deterministic effects), so it's not really weird at all :).

Take it a spin through Valgrind if you're on linux.

UberJumper
May 20, 2007
woop
Is there a way to basically have a templated object (this kinda breaks the point of templates, but humor me) that calls methods corresponding to its type? So i can basically call an overloaded method of function corresponding to its data type.

Or am i just crazy.

shrughes
Oct 11, 2008

(call/cc call/cc)

UberJumper posted:

Is there a way to basically have a templated object (this kinda breaks the point of templates, but humor me) that calls methods corresponding to its type?

How is what you want different from using inheritance with virtual functions? Or, how is what you want different from using typical overloaded functions?

Avenging Dentist
Oct 1, 2005

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

shrughes posted:

How is what you want different from using inheritance with virtual functions? Or, how is what you want different from using typical overloaded functions?

Sounds more like compile-time polymorphism (i.e. "generic functions").

UberJumper, post some code to show what you'd like to do, because I have no idea what you want right now.

UberJumper
May 20, 2007
woop

Avenging Dentist posted:

Sounds more like compile-time polymorphism (i.e. "generic functions").

UberJumper, post some code to show what you'd like to do, because I have no idea what you want right now.

Sorry AD.

Heres a terrible example (im exhausted)

code:
template <typename T> class Foo
{
private: 
	std::vector<std::string> fooVec;
	T somethingstupid;
public:
	Foo(std::vector<std::string> _dumb)
		: fooVec(_dumb)
	{
	};
	
	//Now for fun
	void stupidty(T something)
	{
		std::cout << "Doing Normal T" << std::endl;
	};
	//I want this so when ever T is a string, i want it to do something else
	void stupidty(<I Dont know?> something)
	{
		std::cout << "Do something special for when T is a string" << std::endl;
	};
	//I want this to do something when T is an integer!
	void stupidty(<W?!?!?> something)
	{
		std::cout << "I want to do something else when this dances?" << std::endl;
	};
};
Its a terrible example, but basically depending on the template type of the class, i want it to do something.

Can i do this?

Fecotourist
Nov 1, 2008

UberJumper posted:

Is there a way to basically have a templated object (this kinda breaks the point of templates, but humor me) that calls methods corresponding to its type? So i can basically call an overloaded method of function corresponding to its data type.

Or am i just crazy.

Does template specialization sound like what you're looking for?

code:
#include <string>
#include <iostream>

template <class TYPE>
class Thing {
public:
    Thing(const TYPE &v) { value=v; }
    TYPE GetDoubled(void);
private:
    TYPE value;
};

template <class TYPE>
TYPE Thing<TYPE>::GetDoubled(void) {
    return 2*value;
}

template <>
std::string Thing<std::string>::GetDoubled(void) {
    return value + value;
}

int main(int argc, char **argv) {
    Thing<float> f(3.1);
    Thing<std::string> s(std::string("xyz"));

    std::cout << f.GetDoubled() << " " << s.GetDoubled() << std::endl;

}
produces

code:
6.2 xyzxyz

UberJumper
May 20, 2007
woop

Fecotourist posted:

Does template specialization sound like what you're looking for?

code:
#include <string>
#include <iostream>

template <class TYPE>
class Thing {
public:
    Thing(const TYPE &v) { value=v; }
    TYPE GetDoubled(void);
private:
    TYPE value;
};

template <class TYPE>
TYPE Thing<TYPE>::GetDoubled(void) {
    return 2*value;
}

template <>
std::string Thing<std::string>::GetDoubled(void) {
    return value + value;
}

int main(int argc, char **argv) {
    Thing<float> f(3.1);
    Thing<std::string> s(std::string("xyz"));

    std::cout << f.GetDoubled() << " " << s.GetDoubled() << std::endl;

}
produces

code:
6.2 xyzxyz

Thats exactly what i was looking for. Thanks.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Is there any way in C++ to duplicate the ability of C#'s System.Reflection.Assembly class to instantiate a class based on a string (so for example, passing in "CSomeObject" would return a pointer to a CSomeObject) without using what amounts to a gigantic if-then-else statement?

Right now I have something like the following, and I'm trying to see if there's a way to not have to update that thing every time a new possibility is added to the system (pretend the names aren't obfuscated and there's like two dozen possible actions):

code:
// strAction is retrieved from a DB call
CBase* action;
if (strAction == "CAction1")
   action = new CAction1;
else if (strAction == "CAction2")
   action = new CAction2;
// and so on
(edit) System.Reflection.Assembly probably isn't what I meant, based on googling. Sorry, not much C# knowledge. What I was asking is still clear though, I hope.

Ciaphas fucked around with this message at 16:37 on Apr 16, 2009

TSDK
Nov 24, 2003

I got a wooden uploading this one

Ledneh posted:

Is there any way in C++ to duplicate the ability of C#'s System.Reflection.Assembly class to instantiate a class based on a string (so for example, passing in "CSomeObject" would return a pointer to a CSomeObject) without using what amounts to a gigantic if-then-else statement?
Something like the factory example I posted a few pages ago would probably make your current code smaller and easier to maintain.

You'll still need to have some table somewhere in your code that registers creation objects with the factory, but you can at least make it a bit less of a ball-ache. There are a few ways to make auto-registering objects, but it's a bit more involved, it usually doesn't save you much over the table solution, and you more often than not end up running into static initialisation ordering problems.

litghost
May 26, 2004
Builder

Ledneh posted:

Is there any way in C++ to duplicate the ability of C#'s System.Reflection.Assembly class to instantiate a class based on a string (so for example, passing in "CSomeObject" would return a pointer to a CSomeObject) without using what amounts to a gigantic if-then-else statement?

Right now I have something like the following, and I'm trying to see if there's a way to not have to update that thing every time a new possibility is added to the system (pretend the names aren't obfuscated and there's like two dozen possible actions):

code:
// strAction is retrieved from a DB call
CBase* action;
if (strAction == "Action1")
   action = new CAction1;
else if (strAction == "Action2")
   action = new CAction2;
// and so on

Like said above, a factory is like what you are asking for. Maps and templated functions can help here. Here is my stupid example:
code:
#include <string>
#include <map>
#include <boost/function.hpp>

class CBase {};
class CAction1 : public CBase {};
class CAction2 : public CBase {};
class CAction3 : public CBase {};
class SomeKindofException {};

template <class baseT, class T>
baseT * makeIt() {
	return new T();
};

template<class baseT>
class SimpleFactory
{
private:

	typedef boost::function<baseT* (void)> makeFun;
	typedef std::map<std::string, makeFun> BaseCtrMap;
	BaseCtrMap BaseCtrs;
public:
	SimpleFactory()	{
		AddType<CAction1>();
		AddType<CAction2>();
	}
	template<class T>
	void AddType() {
		BaseCtrs[typeid(T).name()] = &makeIt<baseT, T>;
	}
	baseT *MakeIt(const std::string & name)	{
		BaseCtrMap::const_iterator i = BaseCtrs.find("class " + name);
		if(i == BaseCtrs.end()) {
			throw SomeKindofException();
		}
		return i->second();
	}
};

int main(int argc, char *argv[]) {
	SimpleFactory<CBase> fac;
	fac.AddType<CAction3>();

	CBase * test = fac.MakeIt("CAction1");
	CBase * test2 = fac.MakeIt("CAction3");
}

litghost fucked around with this message at 17:02 on Apr 16, 2009

Null Pointer
May 20, 2004

Oh no!
What's that old adage again? Any non-trivial project ends up implementing a significant subset of Smalltalk?

ehnus
Apr 16, 2003

Now you're thinking with portals!

Null Pointer posted:

What's that old adage again? Any non-trivial project ends up implementing a significant subset of Smalltalk?

Any sufficiently complicated C or Fortran program contains an ad-hoc, informally specified, bug ridden, slow implementation of half of Common Lisp.









Including Common Lisp.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm trying to compile a shared library that also happens to need a static library. How abouts would I do this?

This is what I ran to compile my SO.

code:
gcc -shared -Wl,-soname,libftorrent.so.1 -o libftorrent.so.1.0 ITorrentService.o TorrentService.o
The static library that those .o files needs is called libtorrent.a which also happesn to need Boost. Since it's a static library I assume I don't have to somehow include Boost as well?

I am so confused :smith:.

Please help.

weldon
Dec 22, 2006
I've been working on an MFC program (ver. 6.0), and Am trying to implement a dialog box which will display before the main program. However, i've been having lots of trouble getting this to work. Any tips?

Should the dialog box class be inside of the CFrameWnd class? other way around?

I am trying to have the dialog box allow the user to select the size of the puzzle, which will call a function to set the size.

Should I put the dialog class inside of the puzzle class? Any tips would be greatly appreciated. :)

Whilst farting I
Apr 25, 2006

I'm trying to do a series of input questions, but am getting tripped up on using whitespace.

code:
cout << "Please enter a number: ";
cin >> newNum;

cout << "Please enter a name: ";
cin >> newName.arr;

cout << "Please enter a rank: ";
cin >> newRank.arr;

cout << "Please enter the year: ";
cin >> newYear;
The first and last inputs are integers, the second and third are character arrays.

Whenever I enter something with whitespace, it fucks up everything.

Here's sample output:

quote:

Please enter a number: 011
Please enter a name: Pop Culture
Please enter a rank: Please enter the year:

So I looked up noskipws and thought that would help, but it hasn't. When I try this:

code:
cout << "Please enter a number: ";
cin >> newNum;

cout << "Please enter a name: ";
cin >> noskipws >> newName.arr;

cout << "Please enter a rank: ";
cin >> noskipws >> newRank.arr;

cout << "Please enter the year: ";
cin >> newYear;
I'm met with this bit of lovely output.

quote:

Please enter a number: 011 Please enter a name: Please enter a rank: Please enter the year:

I just want some drat whitespace input in my character arrays, C++! Am I going to have to limit my prompts to single-strings? Like

code:
cout << "Please enter a number: ";
cin >> newNum;

cout << "Name?";
cin >> noskipws >> newName.arr;

cout << "Rank?";
cin >> noskipws >> newRank.arr;

cout << "Year?";
cin >> newYear;
Or is there a less sloppy way to do it?

Vanadium
Jan 8, 2005

The regular formatted input you get using >> take every field as delimited by any whitespace. If you want to read an entire line into an std::string, you can use std::string my_line; std::getline(std::cin, my_line);.

The exact thing that goes wrong for you is that it reads the first word as the rank, then leaves the rest of the input in a buffer. Then that buffer is used to instantly fill the rank variable without giving you a chance to enter anything else.

Fecotourist
Nov 1, 2008
Yeah, let go of the C++ dogma that says "just use cin and cout with << and >>, it's all you'll ever need". Sure, it's cool that those operators are overloaded, and that you can chain them because they return references to the stream, but any use beyond the truly trivial requires way too much other crap to work.

Vanadium
Jan 8, 2005

operator<< and >> are neat for parsing or printing whatever. It is really just that commandline IO with all the buffering and error-flags-instead-of-exceptions and poo poo is unintuitive as gently caress and the operator>> that reads into std::strings is pretty useless.

The Red Baron
Jan 10, 2005

Been having some proof-of-concept fun with Eric Niebler's new mpl::string. Already posted about some of it on the Boost users' list, but didn't seem to garner any attention, so I'm posting it here in case someone gets a kick out of it.

Compile-time itoa() metafunction:
code:
#include <boost/mpl/string.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/push_back.hpp>
namespace meta
{
struct itoa_func
{
  // itoa supports radix 2-36, but only bother with 2-16 here
  typedef mpl::vector_c<char
    ,'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
  > radix_t;

  // Could also have written this as a fold op
  template <int Radix, unsigned int Quotient>
  struct radix_convert
  {
    typedef typename mpl::push_back<
        typename radix_convert<Radix, Quotient / Radix>::type
      , mpl::char_<
          mpl::at_c<radix_t, Quotient % Radix>::type::value
        >
    >::type type;
  };

  template <int Radix>
  struct radix_convert<Radix, 0>
  {
    typedef mpl::string<> type;
  };

  template <int I, int Radix = 10>
  struct apply
  {
    typedef typename radix_convert<
      Radix, static_cast<unsigned int>((Radix == 10 && I < 0) ? -I : I)
    >::type converted_t;

    // Prefix with '-' if negative and base 10
    typedef typename mpl::if_<
        mpl::bool_<(Radix == 10 && I < 0)>
      , mpl::push_front<converted_t, mpl::char_<'-'> >
      , mpl::identity<converted_t>
    >::type::type type;
  };
};

template <int I, int Radix = 10>
struct itoa
  : mpl::c_str<typename itoa_func::apply<I, Radix>::type>
{};
} // ns meta
code:
int main(int argc, char* argv[])
{
  std::cout << meta::itoa<12345>::value << "\n";
  std::cout << meta::itoa<-98765>::value << "\n";
  std::cout << meta::itoa<2009, 2>::value << "\n";
  std::cout << meta::itoa<0xb0057, 16>::value << "\n";
  std::cout << meta::itoa<0xffffffff, 16>::value << "\n";
}
which outputs
code:
12345
-98765
11111011001
b0057
ffffffff
Also did a simple Boost.Functional/Hash-compatible metastring hasher
code:
#include <boost/mpl/string.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/functional/hash.hpp>
namespace meta
{
#pragma warning(push)
// disable addition overflow warning
#pragma warning(disable:4307)

template <typename Seed, typename Value>
struct hash_combine
{
  typedef mpl::size_t<
    Seed::value ^ (static_cast<std::size_t>(Value::value)
      + 0x9e3779b9 + (Seed::value << 6) + (Seed::value >> 2))
  > type;
};

#pragma warning(pop)

// Hash any sequence of integral wrapper types
template <typename Sequence>
struct hash_sequence
  : mpl::fold<
        Sequence
      , mpl::size_t<0>
      , hash_combine<mpl::_1, mpl::_2>
    >::type
{};

// For hashing std::strings et al that don't include the zero-terminator
template <typename String>
struct hash_string
  : hash_sequence<String>
{};

// Hash including terminating zero for char arrays
template <typename String>
struct hash_cstring
  : hash_combine<
        hash_sequence<String>
      , mpl::size_t<0>
    >::type
{};
} // namespace meta
useful for, uhh.. switch-cases at least, and probably other things as well, but who cares about areas of applicability anyway? :colbert:
code:
switch (boost::hash_value("bunnies"))
{
case meta::hash_cstring< mpl::string<'bunn','ies'> >::value:
  std::cout << "bunnies!\n";
  break;
case meta::hash_cstring< mpl::string<'bear','s'> >::value:
  std::cout << "bears!\n";
  break;
default:
  std::cout << "no hash matched\n";
}
All this should be all kinds of deprecated when constexprs and user-defined literals get compiler-support. Which means it probably won't be deprecated for another 10 years or so <:haw:>

Pooball
Sep 21, 2005
Warm and squishy.

drcru posted:

I'm trying to compile a shared library that also happens to need a static library. How abouts would I do this?
Why are you using a static library? If you're using libtorrent-rasterbar, there is a dynamic library available.

quote:

This is what I ran to compile my SO.

code:
gcc -shared -Wl,-soname,libftorrent.so.1 -o libftorrent.so.1.0 \
ITorrentService.o TorrentService.o
The static library that those .o files needs is called libtorrent.a which also happesn to need Boost. Since it's a static library I assume I don't have to somehow include Boost as well?

I am so confused :smith:.

Please help.

A static library, on Linux, is just an archive of object files and doesn't contain linking information. Try this command:
code:
$ pkg-config --libs --static libtorrent-rasterbar
-ltorrent-rasterbar -lz -lboost_date_time-gcc42-1_34_1 -lboost_filesystem-gcc42-1_34_1
-lboost_thread-gcc42-mt-1_34_1 -lpthread -lssl -lcrypto  
I think you can also get this information with libtool but I've never tried.

Whilst farting I
Apr 25, 2006

Vanadium posted:

The regular formatted input you get using >> take every field as delimited by any whitespace. If you want to read an entire line into an std::string, you can use std::string my_line; std::getline(std::cin, my_line);.

The exact thing that goes wrong for you is that it reads the first word as the rank, then leaves the rest of the input in a buffer. Then that buffer is used to instantly fill the rank variable without giving you a chance to enter anything else.

Fecotourist posted:

Yeah, let go of the C++ dogma that says "just use cin and cout with << and >>, it's all you'll ever need". Sure, it's cool that those operators are overloaded, and that you can chain them because they return references to the stream, but any use beyond the truly trivial requires way too much other crap to work.

Using cin.getline had the same result. :(

I am using character arrays, though, not strings.

Here is what I tried.

code:
cout << "Please enter a number: ";
cin >> newNum;

cout << "Please enter a name: ";
cin.getline(newName.arr,20);
newName.len = strlen((char *) newName.arr);

cout << "Please enter a rank: ";
cin.getline(newRank.arr,20);
newRank.len = strlen((char *) newRank.arr);
I tried both cin.getline and getline.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
getline doesn't consume newlines, so the input buffer after a newline looks like "\nbutts butts butts"... and so formatted input operations will assume you entered nothing.

Whilst farting I
Apr 25, 2006

That was something I had seen and tried, too.

code:
cout << "Please enter a number: ";
cin >> newNum;

cout << "\nPlease enter a name: ";
cin.getline(newName.arr,20);
newName.len = strlen((char *) newName.arr);

cout << "\nPlease enter a rank: ";
cin.getline(newRank.arr,20);
newRank.len = strlen((char *) newRank.arr);
Is what you're talking about, right? I tried endl to similar results.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
cin and cout are completely independent. Nothing you do with cout will affect cin. Use istream::ignore.

torb main
Jul 28, 2004

SELL SELL SELL
Alright, I'm feeling a little dumb here. It's been a couple years since I've programmed in C++ (I took two semesters of university courses), so I'm a bit rusty. I'm reading in a file and I keep getting a segfault when reading. Here's the code:

code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>

using namespace std;

int main()
{
    //Open input file
    ifstream infile;
    infile.open("input.txt");
    if(!infile.is_open())
    {
	cout << "Error opening file. Exiting.";
	return 0;
    }
    cout << "File opened." << endl;

    //Open output file
    ofstream outfile;
    outfile.open("output.txt");
    string line;
    cout << "Output file created." << endl;

    //Initialize all register values to 0
    cout << "Initializing arrays..." << endl;
    int register_values[31];
    for(int i = 0; i < 32; i++)
    {register_values[i]=0;}

    //Initialize all memory values to 0
    int memory_values[992];
    for(int i= 0; i < 993; i++)
    {memory_values[i]=0;}

    //Begin reading file
    cout << "Reading file..." << endl;
    infile >> line;
    cout << "1";
    while(!infile.eof())
    {
        //Handling register data
        if(line == "REGISTERS")
        {
		cout << "Reading register data..." << endl;
        	string reg_id;
        	int reg_val;
        	infile >> reg_id;
        	if(reg_id=="MEMORY")
        	{
			cout << "2";
			line = reg_id;
			continue;
		}
        	else
        	{
			cout << "3";
			infile >> reg_val;
			string regnum=reg_id.substr(1,1);
			int temp_num;
			temp_num = atoi(regnum.c_str());
			register_values[temp_num] = reg_val;
		}
        }
        else if(line == "MEMORY")
        {
            //getline(infile, line);
            cout << "4";
            while(line != "CODE")
            {
		cout << "5";
            	string memloc;
            	int memval;
            	infile >> memloc;
            	if(memloc == "CODE")
            	{
			cout << "6";
			line = memloc;
			continue;
		}
		else
		{
			cout << "7";
			infile >> memval;
			int loc_value = atoi(memloc.c_str());
			memory_values[loc_value] = memval;
		}
            }
	}
	else if(line == "CODE")
	{ //future code here
	}
	else
	{
	     cerr << "Invalid input file. Check formatting and try again.       Terminating program." << endl;
	}
    }
    return 0;
}
It seems the segfault is occurring at the very first use of "infile << line;", right below the cout >> "Reading file...". Ignoring all other potentially glaring stylistic flaws in my code, what could possibly be the cause of this?

Input file:
code:
REGISTERS
R1  16
R3  42
MEMORY 
16  60
8   40
CODE
Loop: LD    R2,     0(R1)
      DADD  R4,     R2,     R3
      SD    0(R1),  R4
      DADDI R1,     R1,     #-8
      BNEZ  R1,     Loop
      DADD  R2,     R2,     R4
And output:
code:
[******@cycle1 ~]$ ./mips
File opened.
Output file created.
Initializing arrays...
Reading file...
Segmentation fault
Thanks!!

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
code:
  int register_values[31];
    for(int i = 0; i < 32; i++)
    {register_values[i]=0;}

    //Initialize all memory values to 0
    int memory_values[992];
    for(int i= 0; i < 993; i++)
    {memory_values[i]=0;}
The conditions should be i < 31 and i < 992 — the last element in an array x of size N is element x[N-1], not x[N].

If you want to initialize an array to 0s when you define it, just say int my_array[666] = {}. If you want to zero it again later, use memset() instead of writing you own loop.

Vinterstum
Jul 30, 2003

Alman posted:


int memory_values[992];
for(int i= 0; i < 993; i++)
{memory_values[i]=0;}


You have an off-by-one error here. The memory_values array has 992 elements, but the final pass of the loop sets the 993th element (memory_values[992]) to 0, which is messing up your stack.

Edit: drat.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Jesus dude, pick tabs or spaces, not both. :psyduck:

Also if you're actually going to try to determine where something segfaults, you should be using cerr instead of cout. cout is buffered, and if the buffer isn't emptied before the segfault, you won't see all the data you printed.

Also also, comments like "//Initialize all register values to 0" are kinda useless since the code isn't exactly long/complicated. Adding unnecessary comments is just a way of doubling the amount of maintenance you have to do when you decide to change something.

torb main
Jul 28, 2004

SELL SELL SELL
Haha, wow. Thanks, I'm an idiot. Like I said, it's one of those things where it's been a while.

Avenging Dentist posted:

Jesus dude, pick tabs or spaces, not both. :psyduck:

I wrote some of this at work, and for some reason the text editor I was using had some issues with tabs, so some of that got hosed up and I just haven't fixed it yet. Sorry!

Also, regarding the stupid comments - I understand, it's just that I put them in there as insurance because the professor I'm handing this into is HUGE into documentation.

torb main fucked around with this message at 23:16 on Apr 19, 2009

Dijkstracula
Mar 18, 2003

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

Avenging Dentist posted:

Also if you're actually going to try to determine where something segfaults, you should be using cerr instead of cout.
If you're trying to determine where something segfaults, why are you not compiling with -g and running it through the debugger? I mean, that'll tell you more or less exactly what the problem is.

Avenging Dentist
Oct 1, 2005

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

Dijkstracula posted:

If you're trying to determine where something segfaults, why are you not compiling with -g and running it through the debugger? I mean, that'll tell you more or less exactly what the problem is.

As teapot has taught us (may he rest in peace), a debugger is the last refuge of the incompetent. :colbert:

riggsninja
Jan 15, 2006
Forgive me if this is a dumb question, but my experience with c is limited.

So if I have a struct defined like this

code:
struct abc{int a, b, c, d, e;};
Then in order to get an array of abc's up quickly I can do something like this

code:
    abc arr[] = { {1,2,3,4,5},
                  {1,2,3,4,5},
                  {1,2,3,4,5},
                  {1,2,3,4,5},
                };
But that puts it on the stack, right? If I need the array on the heap, is there a trick for doing something similar? Or once I malloc, do I need to go through arr[0].a = 1; arr[0].b = 2; arr[0].c = 3;... ?

floWenoL
Oct 23, 2002

riggsninja posted:

But that puts it on the stack, right? If I need the array on the heap, is there a trick for doing something similar? Or once I malloc, do I need to go through arr[0].a = 1; arr[0].b = 2; arr[0].c = 3;... ?

The closest you'll get (without knowing the size of the array at compile time) is something like: http://paste.ifies.org/461 (where I'm assuming you want to initialize each struct abc differently), but I'm pretty sure it's C99 only.

Also, the fragment you posted isn't valid C; it would have to be "struct abc arr[] = ...". Are you in C++?

floWenoL fucked around with this message at 10:20 on Apr 20, 2009

fartmanteau
Mar 15, 2007

riggsninja posted:

But that puts it on the stack, right? If I need the array on the heap, is there a trick for doing something similar? Or once I malloc, do I need to go through arr[0].a = 1; arr[0].b = 2; arr[0].c = 3;... ?

Well you can build the struct on the stack like you're doing, malloc() your destination heap memory, then memcpy() from stack to heap. Put that code in a function to clean up memory after. But that would be kinda roundabout. If your purpose is just to pretty your code, it doesn't really matter.

Whilst farting I
Apr 25, 2006

Edit: Now my array is apparently empty.

code:
cout << "Please enter a name: ";
cin.getline((char *)newName.arr,20);
newName.len = strlen((char *) newName.arr);
cin.ignore();

cout << "Please enter a rank: ";
cin.getline(newRank.arr,20);
newRank.len = strlen((char *) newRank.arr);
cin.ignore();

cout << newName.arr << endl;
No matter what I enter for a name, with whitespace or not, it never prints anything but blank spaces. This is such a trivial part of the program, too. Almost everything else is complete. :smithicide:

I'm not sure how much of a difference this makes, but this is embedded SQL, and the way these variables are being declared is like this

code:
EXEC SQL BEGIN DECLARE SECTION;

VARCHAR newName[20];

EXEC SQL END DECLARE SECTION;
Like I said, I can get it to behave just fine without whitespace. This ranges from reading it to inserting it into a table. But any method I try to use to make it read whitespace just totally fucks everything up. I assumed because how it behaves otherwise there's not that big of a difference.

Whilst farting I fucked around with this message at 13:48 on Apr 20, 2009

Avenging Dentist
Oct 1, 2005

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

Whilst farting I posted:

No matter what I enter for a name, with whitespace or not, it never prints anything but blank spaces. This is such a trivial part of the program, too. Almost everything else is complete. :smithicide:

I had it backwards, getline consumes newlines, >> does not. After using >>, you must do the following to make the stream usable for getline:
code:
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
So don't do anything after getline, but if you try to read in numbers before like you were, do that.

Lexical Unit
Sep 16, 2003

The Red Baron posted:

Compile-time itoa() metafunction:
Just curious, did you have some use case for writing this or was this just a "I wonder if I can..." type thing? Pretty neat either way.

Adbot
ADBOT LOVES YOU

The Red Baron
Jan 10, 2005

Lexical Unit posted:

Just curious, did you have some use case for writing this or was this just a "I wonder if I can..." type thing? Pretty neat either way.
Definitely the latter, although I suppose there might be a use case for it somewhere out there since it removes all the need for runtime string allocation and conversion for static integers (Savage OptimizationTM Enabler). Someone on the boost mailing list jokingly posted "now to wait for format<>" in the mpl::string announcement thread, so I thought "... huh :v:".

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