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
Red_Fred
Oct 21, 2010


Fallen Rib
I talked to my tutor and from that I got my checks working. However now I can't do the binary to decimal conversion. I'm trying to use the algorithm that my lecturer showed us but for some reason I get a garbage answer when I print it.

code:
/*Determine if number is valid, if number not valid print error*/
	if (s[0] == '0') {
		s[0] = 'b';
		printf("It's binary.\n");
	} else if (s[0] == '2') {
		s[0] = 'd';
		printf("It's decimal.\n");
	} else {
		printf("Is this number decimal (d) or binary (b)? \n");
		gets(answer);
	}

	/*Process and convert*/
	int a,b,c,d,e,f,g,h,sum;
	if (s[0] == 'b') {
		s[0] = '0';
		sscanf(s,"%d",&num);
		printf("%d",num);
		len = strlen(s);
		*for (int i=len; i > len;i--) {
			a = s[len] * 1;
			b = s[len-1] * 2;
			c = s[len-2] * 4;
			d = s[len-3] * 8;
			e = s[len-4] * 16;
			f = s[len-6] * 32;
			g = s[len-7] * 64;
			h = s[len-8] * 128;
		}
	}
	sum = a+b+c+d+e+f+g+h;
	printf("%d",sum);
	if (s[0] == 'd') {
		s[0] = '2';
		sscanf(s,"%d",&num);
		printf("%d", num);
	}
I know this isn't the best way to do it but it was all I could come up with. It looks clunky as hell. :negative:

Adbot
ADBOT LOVES YOU

Edison was a dick
Apr 3, 2010

direct current :roboluv: only
Well, unless you've got logic elsewhere that converts '1' to 1 then you will have problems with that loop.
'0' is the character that looks like 0, if you treat that character as a number then it comes out to 49. So in your for loop if you were given the string 11111111 then it comes out as 49*1 + 49*2 + 49*4 + ... + 49*128, which is more than 255, which is what 11111111 would represent in binary.
Also, I'm not sure what you're trying to do with the scanf and printf.
EDIT: In fact, I'm not sure what you're doing with most of it.

Edison was a dick fucked around with this message at 23:21 on Aug 2, 2011

mobby_6kl
Aug 9, 2009

by Fluffdaddy
Yeah, I also caught the '0' == 49 thing, but the rest isn't clear at all. Did you mean to comment out the loop? Because it makes no sense if nothing in the loop is using the counter variable. Also, the stuff in the loop will give you problems if len is, say, anything other than 8 (to be honest, I never tried a negative array index. Does it just roll over or what?). Tell us more about what (and how) exactly you're trying to achieve at each step.

nielsm
Jun 1, 2009



Looking at your decimal/binary check first, you've got something messed up.
If both the "first character is '0'" and the "first character is '2'" test fail, you then ask the user for some input. You write that input to a string variable named "answer". But for the two other cases, you write the input type to s[0]. You never check the value of "answer" later either.
(Your check is also not very flexible. What if the user enters "093"?)

Then later, for the actual conversion stuff, you have a loop with an "i" variable as the control variable. But you never reference that variable anywhere in the loop. You also just attempt to handle the entire input on every iteration. You also assume that the input is always 8 characters in that code. You also forget that array indexes start at zero and count to length minus one (visible because you attempt to index the string with its length.) Also check whether there is a number between 4 and 6 :)

Making an integer from a string representing a binary number is really very simple:
number = 0; for (i = 0; i < length; i++) { number *= 2; if (string[i] == '1') { number += 1; } }
If you do read my solution, then explain to me what it does and why it works! (And also tell what happens if the string contains any other characters than '0' and '1'.)

Red_Fred
Oct 21, 2010


Fallen Rib

Red_Fred posted:

Hey guys got a new assignment for a different paper and a new problem! Yay, or something. :eng99:

I need to write a program in C that converts a binary number to a decimal number or a decimal number to a binary number. The rules are I have to use the gets() function (God knows why, from what I have read this things is meant to be avoided like the plague.), decimal can range from 0-255, binary are at most 8 digits.

I'm having trouble getting my checks sorted. So I want to check if the input is either decimal, binary or invalid. I have come up with some ways to do this but none of them seem to work as I want them to.

Here is what I have so far, note the prints at the bottom are me just testing if my checks are working. Thanks for your time!

Okay this post from earlier basically explains what I have to do. So my program needs to figure out if the input value is binary or decimal. If it can't tell it is supposed to ask the user which it is. Invalid input are any other characters that aren't 0-9 or input like 093. I should assume that input beginning with 0 will be binary.

I tried the switch nielsm but I couldn't get it to work and the above is what my tutor suggested I do with regard to input checking. She also said that I should use sscanf to convert from a char array to integers and not atoi which I was going to use. All the printf calls are me just checking things are working along the way. Mobby_6kl yeah that * is not supposed to be there, sorry.

So the tests that are there are supposed to test the first variable that is input. If it is a 0 then the assumption that it is binary is taken, if it is a 2 then the assumption that it is decimal is made. If it is 1 then the user is asked which it is. So far I have just tried the binary to decimal conversion which I'm having a hard time getting my head around (among everything else.)

more falafel please
Feb 26, 2005

forums poster

Otto Skorzeny posted:

yo falafel how'd you get cancered

I posted in LF for three years and don't want to spend $8 so people will take me seriously when I'm talking about technical stuff?

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
That's what I mean, I thought the LF people got decancered when the forum got closed. Guess I was wrong!

TasteMyHouse
Dec 21, 2006

mobby_6kl posted:

I never tried a negative array index. Does it just roll over or what?

It blindly indexes into whatever is in memory before the start of the array, and interprets whatever is there as the type you're looking at (int, float, some class type, whatever). C and thus C++ arrays do no bounds checking.

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

:dukedog:

Having some trouble with converting something to float which also happens to be a pointer.

Note: projectTestFace is a float* and I'm using OpenCV2.2 for the Matrices.

The original:
code:
CvMat *m_projectedTrainFaceMat;
float d_i;
i = 0;
d_i = projectTestFace[i] - m_projectedTrainFaceMat->data.fl[iTrain * m_nEigens + i];
The new version:
code:
Mat *m_projectedTrainFaceMat;
float d_i;
i = 0;
d_i = projectTestFace[i] - m_projectedTrainFaceMat->data[iTrain * m_nEigens + i];
What should I be doing to get m_projectedTrainFaceMat->data[iTrain * m_nEigens + i] to return as a proper float.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Haven't touched OpenCV in a little while, I think you want something like:

code:
m_projectedTrainFaceMat->at<float>(iTrain * m_nEigens + i)
Or perhaps

code:
m_projectedTrainFaceMat->at<float>(iTrain, i)
if m_nEigens is the number of columns and it's set up correctly.

The King of Swag
Nov 10, 2005

To escape the closure,
is to become the God of Swag.
I asked this in the general purpose questions mega-thread last week and didn't get anywhere, so I'm going to try again here and hopefully someone will have a solution.

I'm integrating Lua support into my application and I built both 64 and 32 bit static Lua libraries using TDM-GCC; these of course correlate to the 64 and 32 bit builds of the program I'm integrating Lua into. I have no problem with either build on my 64-bit machine (using gcc flags -m64 and -m32).

I'm on my laptop though and it's 32-bit only, and attempting to build a 32 bit build on it provides me with these errors:

code:
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_mktime32'|
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_time32'|
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_difftime32'|
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_localtime32'|
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_gmtime32'|
Libraries\liblua32.a(loslib.o):loslib.c|| undefined reference to `_time32'|
Libraries\libmss32.a(log.o):log.c|| undefined reference to `_time32'|
Libraries\libmss32.a(log.o):log.c|| undefined reference to `_ctime32'|
Libraries\libmss32.a(init.o):init.c|| undefined reference to `_time32'|
Obviously something is up with <time.h>, but I haven't been able to find the cause or solution. The runtime libraries should also be the same as they're included with the compiler, and the home computer is using the TDM-GCC 64/32 bit compiler and the laptop is running the TDM-GCC 32 bit compiler.

All that said, this only affects compilation. 32-bit builds on the home computer run just fine on the laptop.

Amethyst
Mar 28, 2004

I CANNOT HELP BUT MAKE THE DCSS THREAD A FETID SWAMP OF UNFUN POSTING
plz notice me trunk-senpai
I'm trying to learn the win32 api. My tutor has given each of us a task for the week. My first one was easy enough (a temporary file cleaner), but the second one is to determine weather or not windows is up to date.

I'm reading around on MSDN and there seems to be a COM interface for something called the Windows Update Agent API - http://msdn.microsoft.com/en-us/library/aa387287(v=VS.85).aspx

Now, the interfaces described in here require you to retrieve the coclass that implements these interfaces, I assume there is a CLSID defined for the windows update agent? Where do I find it?

Apologies if this question doesn't make sense, I'm really taking my first steps into COM programming.

EDIT: I figured out that you just prefix the interface name with CLSID_

Amethyst fucked around with this message at 10:28 on Aug 8, 2011

Oxyclean
Sep 23, 2007


I'm a bit confused as to a constructor I was given in a template:

code:
class Course
{
	double m_fee;
public:
	Course(double=0.0);
	Course(Course&);
	virtual~Course();
	bool operator>(Course&);
	bool operator<(Course&);
	virtual void Report()=0;
};
I don't understand the first constructor; what am I supposed to do with it?

shrughes
Oct 11, 2008

(call/cc call/cc)

Oxyclean posted:

I don't understand the first constructor; what am I supposed to do with it?

Implement it.

Oxyclean
Sep 23, 2007


e: realized stupid mistake, ugh.

Forgot about the whole "Course::" poo poo.

e: Right, that too, thanks.

Oxyclean fucked around with this message at 03:31 on Aug 9, 2011

shrughes
Oct 11, 2008

(call/cc call/cc)
That's because one of Course's methods, Report, is declared virtual with no implementation. You'd have to implement a subclass for that.

emonkey
Jun 30, 2007
I'm writing a c preprocessor, and something about visual studio's C preprocessor isn't working as I would expect.

The following code:

code:
int my_test()
{
   return -1;
}

#define my() my_

int main( int argc, char** argv )
{
   return my()test();
}
Obviously this is ugly and nobody should do this. But this does not work with visual studio. Should I be emulating this behaviour? It's treating my_ and test as two separate tokens.

edit: it could just be pasting the newline in

baby puzzle
Jun 3, 2011

I'll Sequence your Storm.
It requires token pasting http://msdn.microsoft.com/en-us/library/09dwwt6y%28v=VS.100%29.aspx

That Turkey Story
Mar 30, 2003

emonkey posted:

I'm writing a c preprocessor, and something about visual studio's C preprocessor isn't working as I would expect.

...

Obviously this is ugly and nobody should do this. But this does not work with visual studio. Should I be emulating this behaviour? It's treating my_ and test as two separate tokens.

edit: it could just be pasting the newline in

Don't try to implement the C preprocessor without referring to the standard. That is correct behavior on the part of Visual Studio. There are plenty of non-compliant C preprocessors out there already (Microsoft's being one of them), the world doesn't need another one!

Hot Dog Day #42
Jun 17, 2001

Egbert B. Gebstadter
One of my friends does a lot of work in C++, and he recommended to me that I don't use .cpp/.hpp pairs but instead do all my method definitions right inside the class definitions in the .hpp file. I trusted him at the time because hey, he does this all day long, but I'm beginning to encounter some difficulties as a result (especially when circular definitions enter the picture).

Is this a respectable practice I should continue or a horror I should purge from my code?

more falafel please
Feb 26, 2005

forums poster

Hot Dog Day #42 posted:

One of my friends does a lot of work in C++, and he recommended to me that I don't use .cpp/.hpp pairs but instead do all my method definitions right inside the class definitions in the .hpp file. I trusted him at the time because hey, he does this all day long, but I'm beginning to encounter some difficulties as a result (especially when circular definitions enter the picture).

Is this a respectable practice I should continue or a horror I should purge from my code?

For templates, you effectively have to do this, but otherwise I don't even see how it's possible without running into massive amounts of link errors?

Hot Dog Day #42
Jun 17, 2001

Egbert B. Gebstadter
Yes, the code uses lots of templates, and my friend is big into generic programming which is probably where the advice came from.

more falafel please
Feb 26, 2005

forums poster

Hot Dog Day #42 posted:

Yes, the code uses lots of templates, and my friend is big into generic programming which is probably where the advice came from.

Template methods effectively need to be in headers if they are used in more than one translation unit, otherwise the compiler is not aware of their implementations at template instantiation time. But in the case of non-templated methods, you're going to run into major problems:

a.cpp:
code:
#include "foo.hpp"

void a()
{
    foo a_foo;
    a_foo.bar();
}
b.cpp:
code:
#include "foo.hpp"

void b()
{
    foo a_foo;
    a_foo.baz();
}
foo.hpp:
code:
class foo
{
    void bar();
    void baz();
};

void foo::bar()
{
}

void foo::baz()
{
}
This will compile but will not link, because all #include does is insert the text of foo.hpp into a/b.cpp. So both a.cpp and b.cpp define foo::bar() and foo::baz(), and the linker won't be able to resolve them.

tractor fanatic
Sep 9, 2005

Pillbug
I think he means defining the methods inline in the class definition.

shrughes
Oct 11, 2008

(call/cc call/cc)

Hot Dog Day #42 posted:

One of my friends does a lot of work in C++, and he recommended to me that I don't use .cpp/.hpp pairs but instead do all my method definitions right inside the class definitions in the .hpp file. I trusted him at the time because hey, he does this all day long, but I'm beginning to encounter some difficulties as a result (especially when circular definitions enter the picture).

Is this a respectable practice I should continue or a horror I should purge from my code?

It's not a horror but it will increase your compile times, and sometimes you will have to put implementations in a cpp file and then you've got some code in cpp files, other code in hpp files, and it's better just to put it all in cpp files, neh? Increasing your compile times is of course a project-dependent problem, but it's been enough of a problem for me to get anal about removing extraneous stuff from headers.

So just put your nontemplated implementations in cpp files, except, perhaps, for really short methods, and except for other general circumstances where you don't give a gently caress.

You certainly aren't coding your project into a corner with this practice, so it's nothing to worry too hard about.

Gerblyn
Apr 4, 2007

"TO BATTLE!"
Fun Shoe

Hot Dog Day #42 posted:

One of my friends does a lot of work in C++, and he recommended to me that I don't use .cpp/.hpp pairs but instead do all my method definitions right inside the class definitions in the .hpp file. I trusted him at the time because hey, he does this all day long, but I'm beginning to encounter some difficulties as a result (especially when circular definitions enter the picture).

Is this a respectable practice I should continue or a horror I should purge from my code?

Purge it. When you look at a class definition, the thing you usually want to see is the function definitions, so you know what you can do with the class. Having all the the code mixed in makes the actual interface of the class much harder to read. As your system gets more complex, the issues you have with circular definitions are likely to just get worse as well.

Java coders (and C# coders, I think) put code into class definitions as standard practice, but they have access to things that C++ coders don't (pure virtual interfaces that actually work properly, plus a different way of importing symbols from other files).

Gerblyn fucked around with this message at 22:35 on Aug 9, 2011

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
The main thing that Java coders have is a language that requires compilers to deal with dependency cycles between different files and classes, instead of a language that requires compilers to process things in exactly the order they were written.

That Turkey Story
Mar 30, 2003

Gerblyn posted:

Java coders (and C# coders, I think) put code into class definitions as standard practice, but they have access to things that C++ coders don't (pure virtual interfaces that actually work properly

:what:

TasteMyHouse
Dec 21, 2006

rjmccall posted:

The main thing that Java coders have is a language that requires compilers to deal with dependency cycles between different files and classes, instead of a language that requires compilers to process things in exactly the order they were written.

This is literally the only thing that I wish C++ had that it isn't getting in 0xb (are we still calling it that or is that joke played out) (besides concepts :sigh:)

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

TasteMyHouse posted:

This is literally the only thing that I wish C++ had that it isn't getting in 0xb (are we still calling it that or is that joke played out) (besides concepts :sigh:)

A good module system for C++ is overdue but I don't think it will ever happen :sigh:

Oxyclean
Sep 23, 2007


So I'm having some problems with this assignment because I'm really unfamiliar with the way he wants us to do things.

The particular problem comes with this line:

code:
char fname[40];
-snip-
m_pStudents->m_Student.GetName() = fname;
(m_pStudents is a struct, containing a student object, m_Student in this case)


When I replace fname with something like "test", it ends up displaying fine when I use cout to print it, but attempting to use a variable, such as fname (which is intialzed with a cin ) causes it to print garbage.

This is the GetName function.
code:
char*& Student::GetName(){
	return m_name;
}
m_name is declared as char* m_name; and is private to the Student class, so I need to use this GetName() function as an accessor. From what I gather, It's returning a pointer to the reference? I feel like this should be obvious, but I'm stumped.

In other words, how do get the contents of the char array into m_name with that accessor function?

E: Thanks, that gave me something to work with.

Oxyclean fucked around with this message at 05:36 on Aug 10, 2011

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Where to start.

GetName returns a reference to a field of type char*. Since it's a reference, the call result is an l-value, and you can assign to it. You are successfully assigning it a pointer that has been produced by "decaying" the array reference to a pointer to its first element, with the result that the value in the field is now a pointer to this local variable. Hooray.

You then presumably return from the function and leave the field pointing to a local variable which has gone out of scope. Some other function, quite possibly the operator<< function, then scribbles all over your poor, abandoned local variable. Boo.

This works with "test" because the storage for the characters in "test" is allocated globally, meaning it exists forever and always.

You need the data to which that field points to live long enough for you to print it. Usually that means allocating it on the heap (and then freeing it later).

Hughlander
May 11, 2005

Visual Studio question...

I open up a vcproj file and see:

code:
    <Tool
        Name="VCCLCompilerTool"
        PreprocessorDefinitions="_Foo=Blah"
    />
However, when I browser the properties from within dev studio, I don't see /D_Foo=Blah in the command line generated nor in any of the options in dialog.

Is there a way to see/set this from within Dev Studio?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Are you looking at the right project configuration?

MachinTrucChose
Jun 25, 2009
I had sworn off C++ (still traumatized over spending hours decrypting the compiler's BS error messages when I was in college), but I just heard about clang. Supposedly, it's a C++ compiler with error messages meant to be understood by other people than those that wrote the compiler. I figured I'd give it a try.

I got it working from the command-line by extracting clang and llvm to my mingw folder, but I want an IDE (any IDE) to use it with.

I tried Netbeans, but it gave me a "mkdir: Command not found" error. I googled it and followed instructions to add the MinGW bin path to Windows' %PATH% environment variable, but I still get that error (though the text surrounding it is different despite the input being the same).

I then tried Qt Creator, which I thought let me use clang++.exe as a compiler, but is still compiling with mingwgcc or whatever in the background. I added a new toolchain where the compiler path points at clang++.exe, then went in my project's options and selected my own toolchain from the dropdown list in place of the default "MinGW as a GCC for Windows target". It seemed simple enough. But I know it's still compiling in GCC because it's giving me GCC error messagess. For example, when I omitted a semi-colon, Qt Creator's compile output said "new types may not be defined in a return type: (perhaps a semicolon is missing after the definition of 'Cat')". If it had been using clang, it would've said "error: expected ';' after class".

I also tried Visual Studio 2010, but there are no options to select a different compiler. I should've known :)

Any advice?

nielsm
Jun 1, 2009



MachinTrucChose posted:

I also tried Visual Studio 2010, but there are no options to select a different compiler. I should've known :)

Any advice?

Actually VC2010 does allow you to choose a different compiler, but the build rules for it have to be defined as a series of MSBuild files. It should theoretically be possible to write a ruleset to allow you to use CLang.
(If you are interested, the relevant files are installed under C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0)


Also, in the specific example you gave last, the error produced by GCC reads just fine to me, it tells you what you have actually written and why it is wrong, and gives you a suggestion for what you might have intended.

TasteMyHouse
Dec 21, 2006

nielsm posted:

Also, in the specific example you gave last, the error produced by GCC reads just fine to me, it tells you what you have actually written and why it is wrong, and gives you a suggestion for what you might have intended.

It's probably template errors that they're worried about.

Hughlander
May 11, 2005

Plorkyeran posted:

Are you looking at the right project configuration?

Unfortunately I am. And I can't find anything on MSDN about this.

raminasi
Jan 25, 2005

a last drink with no ice
When using (TR1) smart pointers, which is a better rule of thumb: use shared_ptrs unless you have a reason not to, or use weak_ptrs unless you have a reason not to? I understand how they both work with respect to ownership, but there are situations where it doesn't seem particularly clear-cut (like passing a smart pointer into a function) and I wonder if there's just some best practices guideline.

Adbot
ADBOT LOVES YOU

TasteMyHouse
Dec 21, 2006

GrumpyDoctor posted:

When using (TR1) smart pointers, which is a better rule of thumb: use shared_ptrs unless you have a reason not to, or use weak_ptrs unless you have a reason not to? I understand how they both work with respect to ownership, but there are situations where it doesn't seem particularly clear-cut (like passing a smart pointer into a function) and I wonder if there's just some best practices guideline.

The way I understand it, use a shared_ptr unless doing so would cause a cyclic reference, in which case use a weak_ptr -- but I'm actually not sure what you think isn't clear cut about passing a smart pointer into a function and I'm curious to hear you elaborate.

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