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
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Your sort algorithm is terrible and broken, your fit function is unreadable, terrible, and broken, and you really need to learn about booleans and structs. But your code is crashing because the numbers stored in num are in the range 1 to k, whereas the valid (first) indexes into box are in the range 0 to k-1.

Adbot
ADBOT LOVES YOU

Jo
Jan 24, 2005

:allears:
Soiled Meat

Ugg boots posted:

Are you sure those values are going to fit into an int?

:doh: :saddowns:

Vandorin
Mar 1, 2007

by Fistgrrl
Im writing a code for a program that makes you guess a number from 1 to 100. The only problem is that when I run it, and enter my number, it shows me everything, it shows me that my number was too high, too low, what close numbers would be, and finally the answer. All I would like it to do is when you enter your number, it tell you if you were too high, or too low, or very close, and then tell you what the number is. Here is my code so far.

code:
#include <iostream>

#include <cstdlib> 

#include <ctime> 

using namespace std;

void main() 
{ 
	int num;
	
	srand( (unsigned)time( NULL ) );
	  
	int randn = (rand()%100)+1 ;
	  
	cout << "Please pick a number from 1 to 100" << endl;
	  
	cin >> num;

	while ( num =! randn )
	if ( num > randn );
		cout << num << "Was too high" << endl;
	if ( num < randn );
		cout << num << "Was too low" << endl;
	if ( num = (randn - 5) );
		cout << num << "Very close!" << endl;
	if ( num = (randn +5) );
		cout << num << "Very close!" << endl;
	if ( num = randn );
		cout << num << "Great job, you guessed it!" << endl;
	system ("pause");
}	

borkzilla
Apr 11, 2008

Vandorin posted:

Im writing a code for a program that makes you guess a number from 1 to 100. The only problem is that when I run it, and enter my number, it shows me everything, it shows me that my number was too high, too low, what close numbers would be, and finally the answer. All I would like it to do is when you enter your number, it tell you if you were too high, or too low, or very close, and then tell you what the number is. Here is my code so far.

Two things:

Take the statement terminators (semi-colons) off of the end of your if statements. Right now those are empty conditions.

code:
if ( num > randn );
		cout << num << "Was too high" << endl;
should be

code:
if ( num > randn )
		cout << num << "Was too high" << endl;
Also, you are using assignment operators instead of comparison operators. In C/C++ a single equal sign is always an assignment, and the result of an assignment matches to true (at least in C). You need to be using a double equal sign to test equality of two values:

code:
if ( num == randn )
Edit:

Wow I didn't read that code very closely the first time through. There are also some serious logical flaws in your program, but I'm not going to re-write the whole thing for you. You need to read a book or at least a simple web tutorial, I'll bet some good ones are recommended in the OP of this thread.

borkzilla fucked around with this message at 18:46 on Jan 23, 2009

Vandorin
Mar 1, 2007

by Fistgrrl
Ok, I got it, the double "==" also solved it showing the "Very Close" part, but and now I only get one of the phrases, which is great :D. Thanks!

edit: Ok, when I try to run it, all it says is "0" and then "Was too low" and no matter what number, it keeps putting the 0 in instead of what I type in.

Vandorin fucked around with this message at 18:48 on Jan 23, 2009

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.

borkzilla posted:

the result of an assignment matches to true (at least in C).
In C and C++, the result of an assignment is the left-hand operand.

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
Also note that '=!' should be '!='; the former will assign the logical negation of the operand on the right to the operand on the left, whereas the latter will test the left and right operands for inequality.

Vandorin
Mar 1, 2007

by Fistgrrl
Ok, I found out how if statements worked, and saw that my code was horrible, here is my attempt to make it better.

code:
#include <iostream>

#include <cstdlib> 

#include <ctime> 

using namespace std;

void main() 
{ 
	float num;
	
	srand( (unsigned)time( NULL ) );
	  
	int randn = (rand()%100)+1 ;
	  
	cout << "Please pick a number from 1 to 100" << endl;
	  
	cin >> num;
	
	if ( num < randn ) {
		cout << "The number is too low " << endl;
	} else if ( num > randn ) {
		cout << "The number is too high " << endl;
	} else if ( num == randn + 5 ) {
		cout << "You were very close" << endl;
	} else if ( num == randn - 5 ) { 
		cout << "You were very close" << endl;
	} else if ( num == randn ) {
		cout << "You guessed right!" << endl;
	}

	cout << randn << " " << "Was the correct number" << endl;
	
	system("pause");

}
It's worked so far, all except the "very close" part, but so far that has been because I have not guessed close enough.

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
Consider the logic you're using for the 'very close' section - what happens if you guess a number that's, say, 4 too high?















look up abs()

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
Also reconsider your use of 'else'; the way you are using it doesn't do what you want it to do.

Vandorin
Mar 1, 2007

by Fistgrrl

Otto Skorzeny posted:

Consider the logic you're using for the 'very close' section - what happens if you guess a number that's, say, 4 too high?















look up abs()

I see what you mean, but I don't understand abs() isn't that just absolute value?

TheSleeper
Feb 20, 2003

Vandorin posted:

I don't understand abs() isn't that just absolute value?

code:
if(abs(randn - num) <= 5)
    //oh man what does that mean and what can I do here?!?!?!

Vandorin
Mar 1, 2007

by Fistgrrl

TheSleeper posted:

code:
if(abs(randn - num) <= 5)
    //oh man what does that mean and what can I do here?!?!?!

Oh whoa, I didn't even think of that, my teacher was telling me to do "range checking" and since he hasn't gone over that part yet, I was wondering how he expected us to do this.

functional
Feb 12, 2008

Here's a question that illustrates my ignorance of C.

If I write a C program, but at some point later decide to include a function that is specifically C++, how much will that affect the performance of my program?

You can assume gcc as the compiler.

Vanadium
Jan 8, 2005

functional posted:

Here's a question that illustrates my ignorance of C.

If I write a C program, but at some point later decide to include a function that is specifically C++, how much will that affect the performance of my program?

You can assume gcc as the compiler.

Apart from the C++ stuff that function needs to initialise and everything, there should not be a performance overhead.

You can write a C-linkage wrapper function of the C++ function and call that from a translation unit that is compiled as C, too.

functional
Feb 12, 2008

I have a void* which I am casting to different types of pointers, e.g., (int*), (mystruct*), etc.

As it turns out, there are several different types I would like to cast to and many different combinations which may occur, so it doesn't make sense to type all the cases out by hand.

Is there some kind of way, using either functions or macros or whatever, that I kind mimic a sort of dynamic cast? What I mean is, I want something similar to a function that returns a different 'casting type,' like
code:
f(0)= (void *)
f(1)= (int *)
f(2)= (mystruct *)
f(3)= (float *)
f(4)= (double *)
f(5)= (long *)
...
so that I can do
code:
mystruct* anything = (f(2)) myvoidpointer;
double* anydouble = ((f(3)) somevoidpointer)[0]  * ((f(4)) anothervoidpointer)[0];
I'm sure this is an old problem. What do people typically do?

Edit: Added some cases to better illustrate the trickiness

Essentially I have a type i associated with each void pointer. I'd like to be able to call f(i) in front of it...

If I have to resort to a custom preprocessor for this, recommendations would be welcome.

functional fucked around with this message at 01:14 on Jan 25, 2009

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

functional posted:

I'm sure this is an old problem. What do people typically do?

If this is C, you can just do mystruct *anything = myvoidpointer; without any cast at all - C99 automatically promotes from void *.

Bunny Cuddlin
Dec 12, 2004
Using this code:
code:
   FILE *inputPtr;
   int numToRead, currInt, currIndex, i;
   char* intArr;
   for (i = 0;i < numToRead; i++) {
      retVal = fscanf(inputPtr, "%d", &currInt);
      intArr[i] = currInt;
      printf("%d:%d|%d ", i, currInt, intArr[currIndex]);
      currIndex++;
   }
I get this output: 0:-340|-84 1:40|40 2:20|20 3:35|35 4:30|30 5:-534|-22 6:45|45 7:60|60 8:75|75 9:-300|-44

Why is it storing -340 as -84?

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Car posted:

Using this code:

You never initialize currIndex, and I'm not clear on why you have it and i. You also never initialize numToRead or open inputPtr, so I'm assuming you're leaving out important bits of the code, without which we can't really help you effectively.

Edit: Also, -340 does not fit in a char, which is what your confusingly-named and never-allocated intArr is made of, and the modulo arithmetic works out to about the right value.

ShoulderDaemon fucked around with this message at 03:18 on Jan 24, 2009

Bunny Cuddlin
Dec 12, 2004

ShoulderDaemon posted:

Edit: Also, -340 does not fit in a char, which is what your confusingly-named and never-allocated intArr is made of, and the modulo arithmetic works out to about the right value.

This is embarassing.

Volte
Oct 4, 2004

woosh woosh
I'm just dicking around with boost::spirit making a parser for a sort of JSON-ish config file format (actually inspired by .irssi/config). The grammar is defined as such:
code:
definition(config_grammar const& self) {
    document            = declarations;
    declarations        = +declaration;
    declaration         = key >> "=" >> val >> ";";
    key                 = +bs::anychar_p;
    val                 = group | arr | bs::longest_d[bs::int_p | bs::real_p] | string_literal;
    group               = "{" >> declarations >> "}";
    arr                 = "{" >> arr_values >> "}";
    arr_values          = val % ",";
    string_literal      = "\"" >> *bs::anychar_p >> "\"";
}
This is supposed to represent a document with the following style:
code:
name = "John Brown";
phone-numbers = {
    "123-456-7890",
    "444-444-4444",
    "987-765-5432"
};
children = {
    {
        name = "Stephanie";
        age = 11;
        gender = "Female";
        lucky-numbers = { 9, 10, 22, 33 };
    },
    {
        name = "Slint";
        age = 21;
        gender = "Male";
        lucky-numbers = { 13, 420, 666 };
    }
};
The problem is, no matter what I put into this parser, be it the above document, a single line, or even a blank string, it enters into an infinite recursive loop and run out stack space. Anyone have any ideas what could be causing this? I'm using space_p as the skip parser if it matters.

Volte fucked around with this message at 07:33 on Jan 24, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
For one thing, your string literals are all kinds of hosed up. The Kleene star is greedy. You should be using a confix parser for them:
code:
string_literal = confix_p('"', *anychar_p, '"')
Also, keep in mind that the space_p parser will cause you problems with key, since it will read "f o o" as "foo". Also also, anychar_p means any char.

Avenging Dentist fucked around with this message at 07:35 on Jan 24, 2009

Volte
Oct 4, 2004

woosh woosh
Thanks, I fixed that as well as changing key to bs::lexeme_d[+(bs::alnum_p | bs::punct_p)]; and it works now. No idea why it doesnt stack overflow anymore... I think maybe VS was loving me over by not recompiling the parser even though I was editing the file, so some old bug stuck around no matter what changes I made. The example document clears the parser now.

The Red Baron
Jan 10, 2005

I posted about my Modern C++ Design-inspired Boost-ified factory patterns some months ago, but I've refined a lot of the code since then and added several new features. I'd really like to hear C&C from some of our resident C++/Boost wizards on what they think of the design/code/documentation etc, and whether or not it seems ready to be submitted to the Boost vault/sandbox any time soon.

Fehler
Dec 14, 2004

.
Can anybody recommend a simple XML parser for C++? All I need it to do for now is parse a string containing XML, allow me to find a certain node and read its contents. There seem to be millions of alternatives and I have no idea which one to choose.

I'm using Dev-C++, if that matters.

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.
TinyXML or TinyXML++ would be the best for such a small use.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
If it's simple and consistent enough, you could also cheat and use regular expressions.

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

OneEightHundred posted:

If it's simple and consistent enough, you could also cheat and use regular expressions.

Depart, ye cursed, to everlasting beta

Bitruder
Nov 29, 2003

Majoring in connect the dots and colouring

Mustach posted:

TinyXML or TinyXML++ would be the best for such a small use.

I used TinyXML in a recent project and it's very simple to use. One thing to note, however, is that in the latest version on their website, it will not parse spaces in attributes of tags (it returns everything UP TO the first space).

POKEMAN SAM
Jul 8, 2004

Bitruder posted:

I used TinyXML in a recent project and it's very simple to use. One thing to note, however, is that in the latest version on their website, it will not parse spaces in attributes of tags (it returns everything UP TO the first space).

What do you mean spaces in attributes of tags? This isn't valid XML: <House The Name="White House" />. Unless you mean spaces in the attribute values, then that's a pretty big bug that would be missed by the TinyXML team.

Volte
Oct 4, 2004

woosh woosh

Ugg boots posted:

What do you mean spaces in attributes of tags? This isn't valid XML: <House The Name="White House" />. Unless you mean spaces in the attribute values, then that's a pretty big bug that would be missed by the TinyXML team.
A quick search revealed that it really is a big bug: http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/160005956931

newsomnuke
Feb 25, 2007

I use MicroXML, does the job very well.

Vanadium
Jan 8, 2005

I use libxml++ because I think everybody should be using C++ and depending on Gtkmm. :geno:

Super Dude
Jan 23, 2005
Do the Jew
(C++)I am trying to grab characters from a string I am reading in from redirecting the cin to a file. Say I have the string "Test" in the file in.txt. I can read the string into my 'string temp' variable. I can write the string to out.txt file as well. My problem is that I want, say, T from the string.

cout << temp[0];

It gives me the following error in gedit when I try to open out.txt

Could not open the file out.txt
gedit has not been able to detect the character encoding.

When I cout to the console, it works fine, but it won't work when writing to a file. What am I doing wrong?

Vanadium
Jan 8, 2005

Could you post the code and attach in.txt or something?

Plinkey
Aug 4, 2004

by Fluffdaddy
Not sure if this is the exact right thread, but I'll give it a shot.

I'm trying to write a managed C++/CLI application and importing an unmanaged C(I think) DLL.

I am using:
code:
[DllImport("RdrData.dll")]
	RD_API DATAPTR RD_new();
It complies but when I try to use the functions from the DLL (memory allocation function RD_new() ). I get a run time error. It's a "System.DllNotFoundException". The DLL and .lib files are in the build directory and looking stuff up on google isn't helping too much. Any ideas?

Olly the Otter
Jul 22, 2007
I've run into a problem with trying to use boost::interprocess for synchronization between several programs. If a program locks a boost::interprocess::interprocess_mutex and then exits or crashes or something before unlocking it, then the mutex becomes unusable by any process.

Here's an example program that demonstrates this: http://pastebin.com/m3432cfe1

Does anyone know of a good workaround for this? The program only needs to run on Windows so I've thought about just using the Win32 synchronization API functions such as CreateMutex -- however, with the flaws in that API I'm not sure if this can even be done correctly. For example, if more than one user is waiting for the same named event, how can we guarantee that they'll all wake up when the event becomes signaled?

Edit: Here's an example with the Win32 API functions: http://pastebin.com/m1ee97c19 This one doesn't end up ruining the shared mutex when a process exits while still holding it, but now if you run more than one instance with Process2 then they just take turns waking up for each update.

Olly the Otter fucked around with this message at 22:51 on Jan 27, 2009

Super Dude
Jan 23, 2005
Do the Jew

Vanadium posted:

Could you post the code and attach in.txt or something?

code:
8
3
# sample input file, three 8x8 floors
#floor 3
XXXXXXXX
X......H
X..X.XXX
X.X..X.X
X..XX..X
X......X
X......X
XXX.vXXX
#floor 2
XXXXXXXX
X......X
X..X.XXX
X.X..X.X
X..XX..X
X......X
X^....SX
XXX.vXXX
#floor 1
XXXXXXXX
X..X.^XX
X....XXX
X..X...X
P..X...X
X...X..X
X...X..X
XXX...XX
code:
cin >> size;
cin >> floors;
int count=0;
int arraySize = (floors*size*size);
char* building = new char[arraySize];

while(getline(cin,temp,'\n'))
{
	if(temp[0]=='#')
	{ 
		comments.push(temp);
	}
	else
	{
		for(int i=0;i<size;i++)
		{
			building[count]=temp[i];
			count++;
		}
	}	
	
}
I suppose I should explain a bit more. We are supposed to start at the point labeled S, and make our way to either the P or the H using a pathfinding algorithm. The floors are arranged in a nxn matrix, with the X being walls, . open spaces...not relevant to my question. Aside from the string class, we can't use the STL. I was planning on inserting all of the floorplans into a 1d array, which would be of size n*n*floors (everything except the top two numbers and the # which start comment lines). I was going to insert the comments into a stack to be reinserted into the out file (this works fine).

The maps are passed to us in a file (such as the one above). We have to write replicas of the maps with our path to another file. I'm using out.txt.

I am running it using: ./proj1 --queue < in.txt > out.txt

It gives the error I mentioned in my previous post when I try to access the buildings array to write to my out file. Also, my count variable (which keeps track of the index in the buildings array) gets up to 199 instead of the 192 max for this example.

Vanadium
Jan 8, 2005

Can you post the relevant parts of proj1

Edit: Like, for example enough code so that it actually compiles, and ideally produces the output that is not to your expectations.

Adbot
ADBOT LOVES YOU

Mr. Manager
Feb 7, 2007
"Well, manager; we just say manager."
When I build a DLL with MinGW, is there any way of having functions with __stdcall but still exporting them as "function" instead of "function@16" and so on? I thought "--add-stdcall-alias" would do that, but it doesn't seem to change anything...

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