>Note: Don't use a try catch
Erm, why? On Error is generally considered to be a huge wart of VB, so why would you want to avoid the superior equivalent in C# and try to emulate it?
>Note: Don't use a try catch
Erm, why? On Error is generally considered to be a huge wart of VB, so why would you want to avoid the superior equivalent in C# and try to emulate it?
My my, such an easy game.
>1. replyfast-c++
Gimme code.
>2. how do I?
Gimme solutions.
>3. Help on java
Gimme code.
>4. java game code
Gimme code.
>What I am trying to say here is can't people
>read the forum guidelines before posting.
No. They don't care, so why should they?
Are you linking with a library file or DLL as well, or just including the header?
>Persistent storage of information is written to disk (aka file IO).
I think you misunderstood. I'm not saying never to store passwords, I'm saying never to store passwords in a form that can be reversed. That includes encryption, which in my experience typically means a reversible encryption.
>In many cases, the credentials are passed on
I was talking about storing a password for authentication purposes, not further using the password for other purposes or with differing authentication schemes.
>Personally, I prefer to use Active Directory for all authentication
Indeed. This is also a more user friendly option as you can lose the login dialog altogether and simply rely on Windows to authenticate the user for you. That's not always possible, but it's a good general approach.
>How do I prevent the user from entering characters when a float is required?
There's no standard way to stop a user from entering a character. You'd have to use a non-portable solution or allow anything under the sun and provide robust validation. I always recommend going for the portable solution first, and fortunately, your case is easy to validate:
bool valid = false;
do {
cout<<"Please enter the CD cost: ";
if ( cin>> usrcost ) {
if ( usrcost > 0.0 )
valid = true;
}
else {
// Clear the error state
cin.clear();
// Clear the stream of all characters
cin.ignore ( 1024, '\n' );
}
} while ( !valid );
>which one is best DLL/SLL
Neither, it depends on your needs.
>So, store the username and password in a file (encrypted I hope),
>and on startup, if the file exists, load up the information.
Ugh, no. Even encrypted, don't copy the password anywhere, period. Ideally you wouldn't even store it for authentication, instead favoring an irreversible hash[1]. The only place a string that can be restored to the original password should be allowed is the input box, and even then it should be discarded as quickly as possible.
You have the right idea though. Store some kind of identifying information for the user name that tells the application that this user's password is valid as long as it remains unchanged in the form on subsequent logins. That means poll for a TextChanged event and require a password for that session if it gets fired.
If you're properly masking the password in the input box then it really doesn't matter whether you put the right password there or not. Of course, if your system is even remotely secure, you wouldn't know the right password anyway. That's something only the user should have access to in any way, shape, or form. Just fill the box with enough garbage to make it look like there's a password there.
This way the password remains secure, even if the whole idea of "remember my password" isn't. ;) Just FYI, since this talk of security, hashes, and such is probably well beyond the OP at the moment. Also, somehow I doubt that …
>Would I attach pragma once here as well?
I don't see why you would need to unless you actually include register.cpp in another file. Otherwise, it'll work without the #pragma because implementation files must only have one instance in the translation unit or you'll get multiple definition errors. #pragma once is a non-portable equivalent for inclusion guards in headers, nothing more (barring compilation optimizations). If #pragma once is supported then:
#ifndef UNIQUE_NAME
#define UNIQUE_NAME
// Header shtuff
#endif
Is (probably) functionally identical to:
#pragma once
// Header shtuff
>I had something like this in mind
That defeats the purpose of a constructor. It's also no better than leaving the object in an uninitialized state if the constructor fails, because you have an "initialized--just kidding" object that's in a limbo state until you call a member function. That kind of interface design is painful to use.
>you have to put the whole class in try/catch which might be undesireable or even not possibe
So you'll penalize all users of the class based on a rare or hypothetical test case?
>In the above obj can not be used outside the try block.
Nor should it, if you're using exception handling properly. Also, keep in mind that thrown exceptions unwind the call stack until a catch is found. So if the try block bothers you that much, you can rely on a catch higher up. For example:
void blah()
{
foo obj;
}
int main() try
{
blah();
}
catch ( ... ) {
// Handle errors
}
Now you're using obj "outside" a try block, but it's still protected by a catch higher up in the call chain. Or you can even ignore the exception altogether and rely on the default behavior of terminating the program.
>i tried but my problem is about randoms in queue
You have two problems:
Solve them separately. Conveniently enough, searching the forum for either (but not both) of those problems will give you previously asked questions that you can use to complete your homework.
>Is there a workaround?
Switch to Code::Blocks. The underlying compiler is the same (gcc with MinGW), and the IDE is vastly superior in my opinion. Also, Dev-C++ is no longer under development and Code::Blocks is being actively worked on.
>Is aesthetics important?
The answer is subjective. I think aesthetics are important across the board, including the color scheme for my code editor. I choose colors that are pleasing and don't strain my eyes. I'll change my color scheme regularly as well. Others may not care how the code looks at long as it's well written.
>I've always read that you should never put code
>in a constructor that might cause an exception.
Perhaps you're thinking of destructors and the whole throwing an exception while processing an exception nightmare. The best way to handle a fatal error in the constructor is to throw. Otherwise you're stuck with a partially constructed object, and that way lies madness.
>For example if you need to allocate memory in the contructor then put it in
>an Initialize() method where the exception can be safely caught and/or thrown.
If you're calling the method from the constructor, you've still got the same problem: dealing with a thrown exception within the constructor call chain. Catching an exception can be done in the constructor as well; adding another level of abstraction doesn't change anything if you catch. In fact, it's a good solution (catching and rethrowing) because you have to clean up your mess before throwing a new exception or rethrowing. Destructors aren't called if the constructor throws.
>if the constructor of ClassTest throw exception, what will happen?
Why don't you try it and see?
>will ptr == 0 ?
That's a good assumption.
>some memory leak?
It depends on what throws the exception and how you deal with it. If your constructor allocates memory but doesn't release it when the exception is thrown, you have a memory leak.
That's...random. I suppose you're using your first post to show off your m4d pr0gr4mm1ing sk1llz. :icon_rolleyes:
Generating random numbers is a common question here. Try searching the forum.
The most irritating bug I've encountered is mixing up << and >> in C++ iostream operations. It's irritating because I do it all too often and I know better.
>the longest to fix
Probably intermittent data corruption in a very complicated parser. It took me forever to find the source of the problem, fix it, and verify that the fix didn't break anything else due to the painfully intricate logic.
>the most complex to fix
Definitely a subtle bug in a file system. It seemed like every part of the OS relied on the buggy behavior, so I had to make sweeping changes across the entire code base to correct the problem.
>the most unsatisfying fix
Pretty much every bug that's so fundamental I have to go back to the design stages. I have trouble wrapping my head around relational logic, so most of my database designs end up with at least one of these. ;)
>How can I use templates with generic data nodes?
Store polymorphic objects or pointers to void.
>perhaps my real problem is that the poster forced me to review some
>of my earliest posts here, making me think "eww. did i really post that?"
Feh, welcome to the club. I wish I could delete some of my oldest posts on cprog because they're so horrible.
>to a thread that was dead for 2 1/2 months.
The comment was relevant, so it doesn't matter how old the thread is.
>did you have a better solution?
I'd say it was a fair warning to those who might unknowingly use the algorithm thinking that it's bulletproof, whether he had a better solution or not.
>while ((score = sr.ReadLine()) != null)
ReadLine returns a string, not a double. There's no implicit conversion from string to double, so you have to make the conversion manually:
string line;
while ( ( line = sr.ReadLine() ) != null ) {
double score = double.Parse ( line );
//...
}
>I'd advise to use an arraylist for that.
I'd advise against the non-generic collections unless you have a good reason (such as compatibility with the framework prior to .NET 2.0). Rather than ArrayList, use List<> from System.Collections.Generic.
>I get the impression that everybody thinks the mighty narue is so intelligent
Everybody would be disappointed then. I'm not exceptionally intelligent, I'm just too stubborn to give up. ;)
>The code presented by Jepthah will not correctly vaildate 12..3 or 12.b.rr.3 and the like
Validating floating-point is surprisingly difficult, especially if you choose to allow exponent formatting. I imagine jephthah was keeping the algorithm simple, because to do it right means a lot of added complexity. Here's something relatively complete and much more formalized than jephthah's, and I still wouldn't claim that it allows all valid strings and catches all invalid ones:
#include <ctype.h>
static int is_sign ( int ch )
{
return ch == '-' || ch == '+';
}
static int is_fraction_boundary ( int ch )
{
/* Allow for variations such as "-.1" and ".1" */
return isdigit ( ch ) || ch == EOF || is_sign ( ch );
}
/*!
<summary>
Validates a string for with floating-point format rules
</summary>
<param name="src">The string to validate</param>
<returns>
A pointer to the character at which validation stopped. For
successful conversions on a non-empty string, this will be a
pointer to the null character.
</returns>
<remarks>
Conversion rules (grammar):
floating-constant:
sign(opt) fractional-constant exponent-part(opt)
sign(opt) digit-sequence exponent-part
sign(opt) digit-sequence
fractional-constant:
digit-sequence(opt) . digit-sequence
digit-sequence .
exponent-part:
e sign(opt) digit-sequence
E sign(opt) digit-sequence
sign: one of
+ -
digit-sequence:
digit
digit-sequence digit
</remarks>
*/
const char *is_float_format ( const char *src )
{
int in_exponent = 0; /* When true, exponent-part rules apply */
int in_fraction = 0; /* When true, fractional-constant rules apply */
int seen_digit = 0; /* When true, src contains a digit */ …
>thanks alot but it didn't print the array elements
I know that. That's why I said, and I quote, because you obviously didn't read it: "That's not going to print the contents of a student object.".WriteLine doesn't know what a student class is, so how can you expect it to print the members correctly? It's treated as an object and printed accordingly. If you want to print the members, you do so manually:
Console.WriteLine ( array[0].name );
Console.WriteLine ( array[0].gender );
Console.WriteLine ( array[0].tel );
Console.WriteLine ( array[0].classe );
Clearly my original helpful comment wasn't enough for someone who wants to be spoonfed.
>Shoot the Iraqis carrying Evian bottles because [Evian] is manufactured in France.
Haha.
>Wait until evening prayers, then bomb the mosque.
Bwahaha!
I got 11 out of 19, probably because I focused too much on preserving potentially innocent lives. :icon_rolleyes:
>so what evidence, precisely, did he use to accuse you of not being a real blond
Comparison of my picture with a picture of his wife. Probably a straight color comparison.
>Does that make sense?
Absolutely. Unfortunately there's not a standard strrstr function, so the most straightforward solution is to save the previous match until strstr fails. At that point you know you've got the last instance of the substring:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "LTD STEPHEN LTD JOHNSON LTD";
char *match = company;
char *last = NULL;
while ( ( match = strstr ( match, "LTD" ) ) != NULL ) {
last = match;
match += 3; /* Skip the match so we don't loop forever */
}
if ( last != NULL ) {
memmove ( last + 7, last + 3, strlen ( last + 3 ) );
memcpy ( last, "LIMITED", 7 );
puts ( company );
}
return 0;
}
Of course, that might not be a perfect solution if by "not the end" you mean the last word in the string. In that case both the test and replacement are conceptually easier, especially if you don't care about trailing whitespace:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "LTD STEPHEN LTD JOHNSON LTD";
size_t i = strlen ( company );
do
--i;
while ( isspace ( company[i] ) );
if ( i >= 2 && strncmp ( &company[i - 2], "LTD", 3 ) == 0 )
strcpy ( &company[i - 2], "LIMITED" );
puts ( company );
return 0;
}
>student []array = new student[x];
This creates an array of references to student objects. It doesn't create the actual student objects. You need to do that as well in your loop:
student[] array = new student[x];
for ( int i = 0; i < array.length; i++ ) {
array[i] = new student();
//...
}
>Console.WriteLine(array[0]);
That's not going to print the contents of a student object.
>"<img.*src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1\\S+))" but it doesnt work
Erm, why not just this?
private HasAttribute ( string src, string tag, string attribute )
{
string query = "<" + tag + ".+" + attribute + ".+>";
//...
}
All you're doing is checking a specific tag to see if it has an alt attribute, right?
Finding examples of the regular expression library in C# is easy, so I'll leave that to you. The regular expression you want might be something like this:
">\s*\d+\s*<"
What this does is look for any number with one or more digits (+\d), surrounded by > on the left side and < on the right side with optional whitespace between. It'll pick up any HTML element value that's just a number, so if you want to match just table data elements, you can be more specific:
"<td.*>\s*\d+\s*</td>"
Now the regular expression matches an opening tag of "<td" followed by any number of attributes, the value string as before, and also the closing tag of "/td>.
If you know the string is big enough to hold all of the extra characters, it's a relatively simple matter of finding instances of "LTD", shifting everything after the matched substring (to make room), and copying the new substring in:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "STEPHEN JOHNSON LTD";
char *match = strstr ( company, "LTD" );
if ( match != NULL ) {
memmove ( match + 7, match + 3, strlen ( match + 3 ) );
memcpy ( match, "LIMITED", 7 );
puts ( company );
}
return 0;
}
>Yeah, why do you have a Kyon avatar?
I like Kyon. I can relate to him dealing with all the crazies around here. ;)
Dani insists otherwise, but I still think most of our visitors are web crawlers.
>Pls help me in finding hcf and lcm of 2 nos
It's easy. All you do is grab the igm, do a qp on the xt half of the pgid and roll everything up into a qt7-qualified czsm. Hope that helps! :)
Of course. Just add them to a running total right after you print them. When the loop is done, you'll have a sum of all of the printed random numbers.
FYI: It's somewhat difficult to pinpoint syntax errors when we can't see the code. So post the code.
Template tip #1: Write your class first using concrete types (such as int) and get it working. Then add the template parameters and replace instances of the concrete types with the parameters. This skips the whole "a template isn't instantiated until you use it" crap, which tends to hide simple errors until you actually touch the code in your test driver.
Template tip #2: During initial development, define all of your member functions in the class definition. That way you don't have to deal with the mess of properly linking a member function definition to a template class. Compare:
template <typename T>
class Foo {
public:
void test ( T arg )
{
// Stuff
}
};
template <typename T>
class Foo {
public:
void test ( T arg );
};
template <typename T>
void Foo<T>::test ( T arg )
{
// Stuff
}
I don't know about you, but duplicating the template parameters and qualifying the class name in an outside member function definition is tedious and tends to verbose when all you really care about at this point is getting the code working. After it's working you can easily convert example #1 into example #2.
Note: You're using the format of example #2, but it's incomplete, which is why you're getting errors.
Sorry, I have more integrity than to assist in the decay of Wikipedia.
>toString has to be declared using a template because it
>should be able to convert 3 different types of numbers.
I don't see the problem. You have a global toString function that takes a template argument. You have a virtual toString member function that presumably calls the global function. The only thing you're missing is an overloaded << operator for the derived classes to be able to use the global toString function:
template <typename T>
inline string toString(const T& t)
{
stringstream ss;
ss<<t;
return ss.str();
}
class Number
{
public:
virtual double getValue()const=0;
virtual string toString()=0;
};
class Double : public Number
{
private:
double value;
public:
Double(double v):value(v){}
~Double(){}
double getValue()const {return value;}
string toString() {return ::toString ( *this );}
friend ostream& operator<< ( ostream& out, const Double& num )
{
return out<< num.value;
}
};
>Should the implementation be based on front and
>rear and just change the value of front and rear.
Yes. When you add an item (stack as the example), add to the rear and increment it. If incrementing it would put it beyond the last element, reset it to 0. When you remove an item, decrement the rear. If decrementing it puts you into the negatives, reset it to the last element. Then return the rear value.
>the problem is that the program will have an empty cell between rear and front.
That's not a problem if you use an item count to determine if the array is full or empty:
#include <iostream>
#include <stdexcept>
template <typename T, int N>
class stack_type {
T _base[N];
int _front;
int _back;
int _size;
public:
stack_type()
: _front ( 0 ), _back ( 0 ), _size ( 0 )
{}
bool empty() const { return _size == 0; }
bool full() const { return _size == N; }
void push ( T data )
{
if ( full() )
throw std::runtime_error ( "Stack is full" );
_base[_back] = data;
if ( ++_back == N )
_back = 0;
++_size;
}
T pop()
{
if ( empty() )
throw std::runtime_error ( "Stack is empty" );
if ( --_back < 0 )
_back = N - 1;
--_size;
return _base[_back];
}
};
int main()
{
stack_type<int, 3> stack;
for ( int i = 5; !stack.full(); i-- )
stack.push ( i ); …
>The method has to be declared using a template.
Why? What does this method do? Can you post your code?
What have you tried so far? Have you worked out the tasks that need to be performed?
>why do programmers benifit from having such a variety?
They can choose the data type that best fits the problem and optimize speed or storage costs.
>Also if anyone could help me out with what an unsigned character is used for?
Off the top of my head: If you don't want negative numbers, if you want to extend the range of signed char but don't want to jump up to short int, if you need the wrap-around qualities of an unsigned type, if you want to store an object in an array of bytes (unsigned char is the only type guaranteed not to have padding bits).
The majority of posters aren't interested in being a part of the community. They have a question and bail as soon as it's answered or as soon as it's clear they won't get a "satisfactory" answer.
God, does your ego really need so much stroking that you would lie to keep your bogus Wikipedia article alive?
>whereas yours is 125x125
I could have sworn it was 100x100 when I uploaded it. Come to think of it, it was probably shrunk down which is why the animation didn't work originally. Heheh. :$
>I'm not quite sure why the system allowed Narue to upload something larger!
A change from the mod panel sidesteps the size restriction, but I honestly thought it was 100x100, so I really wasn't trying to abuse my power. gomen.
>PS: Which anime is that Narue chan?
Suzumiya Haruhi no Yuutsu.
>Narue, are you a girl?
I am. Are you surprised? ;)
>I think im just going to go with the real pic of myself as a personal touch.
Rashakil Fol did that and I called him a serial killer. I showed Dave Sinkula my picture and he tried to convince me that I don't really have blonde hair... Real pictures are nothing but trouble. By the way, I think you'd look hotter without the face fur.
>is you real name Narue?
No, my real name is Julienne.
Um, you're a moderator. If I recall correctly I've benefited from the PM limit increase far longer than I've been super mod, so I'd wager that you've got access to the extra features too.