Narue 5,707 Bad Cop Team Colleague

>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 );
Narue 5,707 Bad Cop Team Colleague

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. ;)

Narue 5,707 Bad Cop Team Colleague

>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! :)

hammerhead commented: Helped me lol +2
Narue 5,707 Bad Cop Team Colleague

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.

Narue 5,707 Bad Cop Team Colleague

I gave you my ideas already. I'm not going through that mess of code to tell you exactly what to fix. You're just going to have to remove valid chunks until you find the problem area.

Narue 5,707 Bad Cop Team Colleague

The simplest method is to break when randomNumber is one of those values:

if ( randomNumber == 5 )
  break;

That gets a little tedious when the list of numbers to break on is long, but you can easily scale it up with a collection:

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <set>

int main()
{
  int init[] = { 1, 2, 5, 7, 9, 14, 18 };
  std::set<int> ignore ( init, init + 7 );

  srand ( (unsigned)time ( 0 ) );

  int r;

  do {
    r = rand();
    std::cout<< r <<'\n';
  } while ( ignore.find ( r ) == ignore.end() );
}
Narue 5,707 Bad Cop Team Colleague

It means you have a mismatched brace or double quote somewhere. The parser is reaching a logical end-of-file before the actual end-of-file and choking on the syntax error.

Narue 5,707 Bad Cop Team Colleague

>so there's no way to get the length of record directly?
No, but you're already assuming that the maximum length of a record is 99 characters, so I don't really see how the length matters. Why not build the length array as you need it, and instead of storing the record length, store the offset of the record. Something like so:

recordLen: array[0..830000]
n: int as 0

# The first record is always at offset 0
recordLen[n] := 0

while count < MAX_READ do
  randNum: int as rand() % 830000

  if randNum > n then
    # Fill the lengths up to randNum
    seek fp to recordLen[n]

    # Build the offsets up to randNum
    while n < randNum and read str from fp do
      n := n + 1
      recordLen[n] := recordLen[n - 1] + length str
    loop
  else
    seek fp to recordLen[randNum]
  endif

  # At this point we're at the correct offset
  read str from fp

  # Process str

  count := count + 1
loop

That way you only read as much of the file as necessary. There's also an added benefit of being able to calculate the record length from the offsets if you need it. As long as seeking is quick, you should see at least some improvement, unless you're unlucky and you hit the upper end of the random range immediately. ;)

Narue 5,707 Bad Cop Team Colleague

The location of the executable isn't required to be in the current working directory. What OS and compiler are you using?

Narue 5,707 Bad Cop Team Colleague

>While I'm no expert at C++ I think I can help you with your dilema.
I don't think you can, sorry.

>I use the library time.h so you'd want to add
time.h is deprecated in standard C++. New code should be written using the ctime header instead.

>this is all assuming that you have using namespace std; in
>there as well, although I'm not sure that time.h requires it.
time.h does not place any names in the std namespace, but ctime does.

>Anyway the main two things you want to use are clock() and clock_t
Did you even bother reading the thread before replying? We've already established that the OP wants to work with date/time, not clock ticks.

>clock_t FiveSecondsLater; // This declares your time variable
>FiveSecondsLater = clock() + 5 * CLOCKS_PER_SEC;
That's nice. Now explain how that can be used to given the current wall clock time for different timezones.

>Another function you could do here would be a generic "wait" function.
Which is an extremely bad idea. A busy wait is both inefficient and anti-social.

Narue 5,707 Bad Cop Team Colleague

>Is there somewhat better way to type the code below?
Are you simply asking for advice on working code, or are you having problems with it? I can see areas where mixing and matching types (both ranges and signedness) may get you in trouble.

If all you want is ways to improve the code then to simplify matters, I would get rid of data and just use a slice of buf:

for ( i = 0; i < filesize; i += 8 ) {
  stat = canWrite ( hnd, 1234, buf + i, 8, canMSG_EXT );

  if ( stat < 0 ) 
    printf ( "Failed, status == %d\n", stat );

  stat = canWriteSync ( hnd, 500 );
}

And you can refactor that while writing piece because everything is the same except for the pointer to your eight bytes:

int networkWrite ( unsigned char *start )
{
  if ( canWrite ( hnd, 1234, start, 8, canMSG_EXT ) < 0 ) 
    printf ( "Failed, status == %d\n", stat );

  return canWriteSync ( hnd, 500 );
}

Then the two blocks of code become:

/* Send away INFO about the file's size */
size = filesize;
stat = networkWrite ( size );
	
/* Divide up the file about 8 byte and send it */
for ( i = 0; i < filesize; i += 8 )
  stat = networkWrite ( buf + i );

However, since size is an unsigned int, you have an issue if int …

Narue 5,707 Bad Cop Team Colleague

Why use fread at all? fgets seems to be a better fit for your problem, especially since you're using it anyway to preprocess the record lengths. The more input requests you make, the slower your code will be, so if optimization in your goal, minimize the number of calls that read from the file.

Ideally you would keep a portion of the file in memory at any given time, but it's difficult to make this efficient when the access pattern is random.

Narue 5,707 Bad Cop Team Colleague

That's slightly harder, but you have more control and it's actually portable:

#include <ctime>
#include <iostream>

int main()
{
  std::time_t now = std::time ( 0 );
  std::tm *local = std::localtime ( &now );

  local->tm_hour -= 6;

  std::time_t before = std::mktime ( local );

  std::cout<<"Now:         "<< ctime ( &now ) <<'\n';
  std::cout<<"6 hours ago: "<< ctime ( &before ) <<'\n';
}

C++ supports something called a clock, and means system clock ticks, not wallclock time. Keep that in mind when asking questions about the "clock", because what you actually want to manipulate is date/time.

Narue 5,707 Bad Cop Team Colleague

To what end? You can easily call std::clock() to get the current value and perform math on it. But the result may not be meaningful.

Narue 5,707 Bad Cop Team Colleague

If I understand your question correctly, you want to return a reference to one of the structure instances inside your object:

#include <iostream>

struct block {
  int data;
};

class block_collection {
  static const int _size = 10;

  block _base[_size];
public:
  int get_size() const { return _size; }
  block& get_block ( int i ) { return _base[i]; }
};

int main()
{
  block_collection blocks;

  for ( int i = 0; i < blocks.get_size(); i++ )
    blocks.get_block ( i ).data = i;

  for ( int i = 0; i < blocks.get_size(); i++ )
    std::cout<< blocks.get_block ( i ).data <<'\n';
}
Run.[it] commented: Cheers again! +1
Narue 5,707 Bad Cop Team Colleague

What kind of manipulation are you looking for? Standard C++ pretty much only gives you query capabilities for the clock, though you have comprehensive time and date control.

Narue 5,707 Bad Cop Team Colleague

>Well, it is fairly obvious where the changes are, but I added
Not at a glance, especially with the messed up indentation you used, and I'm not interested enough to compare the two programs line by line to find your changes.

Narue 5,707 Bad Cop Team Colleague

>this should work.
Please specify what changes you made, and ideally why you made them.

Narue 5,707 Bad Cop Team Colleague

Well, that's the same thing that you posted before. However, it's not a common variation of the "I want to make a triangle" crowd, which is why I suggested that the forum is messing up your careful formatting.

Narue 5,707 Bad Cop Team Colleague

If you want to use the copy template, really all you can do is make sure the vector is sized correctly:

v.resize ( n );
std::copy ( a, a + n, v.begin() );

Alternatively, you can do this straight from the constructor of the vector object and not have to worry about any of that stuff:

std::vector<int> v ( a, a + n );
Narue 5,707 Bad Cop Team Colleague

>Does anything that I've put jump out as an error I've made?
Yes, I see one problem if the vector doesn't already have a size equal to or greater than the size of the array: copy doesn't call push_back, it performs a direct assignment. I'd do something more like this:

#include <algorithm>
#include <iterator>
#include <vector>

const int n = 25;

int a[n];
std::vector<int> v;

//...

std::copy ( a, a + n, std::back_inserter ( v ) );
Narue 5,707 Bad Cop Team Colleague

Um, what? I'm not sure I understand what you're trying to ask.

Narue 5,707 Bad Cop Team Colleague

I believe the first C compiler was written in assembly language. Subsequent compilers have been written primarily in C and later, C++. However, that has nothing to do with learning C. You're really better off focusing on learning the basics of the language and saving history for later.

Narue 5,707 Bad Cop Team Colleague

We have an active forum devoted to C. I'd wager that one or two of us know it. Can you be more specific about "how C can be made"? Do you mean how to compile C source? How to write a compiler?

Narue 5,707 Bad Cop Team Colleague

Sorry, but you're going to have to fix the formatting of your triangles. I added code tags to preserve the spacing, but it looks like you used Daniweb's input box to format everything. The input box doesn't use a fixed width font type, so what looks good when you type it looks like crap when it's submitted. Use a text editor with a fixed width font to get your triangles right, then paste them into code tags.

Narue 5,707 Bad Cop Team Colleague

>I would like to hear an explanation on why I can't do this.
Because you never told p where to point. Thus, it could point anywhere, and "anywhere" is very likely outside of your address space.

Google Spider commented: Coz she helped me with my dumb question* +1
Narue 5,707 Bad Cop Team Colleague

Throw a standard exception. You can find a few in <stdexcept>.

Narue 5,707 Bad Cop Team Colleague

Please tell us what kind of problem you need help with. We can't offer anything more than general advice if you don't specify what's wrong with your code.

Narue 5,707 Bad Cop Team Colleague

Use spaces instead of tabs, and this problem will pretty much go away. I know that's not a "real" solution, but it's a workaround until Dani admits that there's a problem. ;)

Narue 5,707 Bad Cop Team Colleague

>can you even remember learning the basics how to program?
I remember my struggles quite clearly, thank you.

>im just offering the simple answer for simple questions. for clarity.
Fine. Do whatever you want. I'm tired of fighting the same losing battle with every yahoo who thinks he's helping because he makes people happy in the short term.

Narue 5,707 Bad Cop Team Colleague

>i rarely use atoi, favoring strtol instead. and i always
>error check user inputs in my own code.
I couldn't care less about your own code. You can use every bad habit in the book for your private programs, but the around here, we set a good example for programmers that usually don't know any better.

>why doesnt "x" work? with a simple answer: because
>you can't use "x" like that... you must use "y" instead.
In my experience, they're going to take your word as the word of God and use "y". If you're giving an example, make sure it's a good example, because it's a safe bet that someone will use it in a serious program.

Rather than give a specific solution (especially a bad one), explain why "x" doesn't work and the process that leads to "y". Then you can list standard functions that do "y". For example, "use atoi" is bad, but "you have to convert the string to an integer, and here are a few functions that do it for you...".

>you've already won.
I'm not here to win, but as long as you keep encouraging bad habits, I'll continue to feel like I've lost.

Narue 5,707 Bad Cop Team Colleague

>i dont think it's helpful to hand a beginner a fully fleshed out production-quality routine
I agree. However, I also don't think it's helpful to dumb down your examples to the point of being blatantly wrong. My post was more for you than for him.

>i say let them send invalid args to the commandline and see what happens.
In which case it might work still "work", if the undefined behavior doesn't constitute a crash and they see atoi returning 0 as legitimate behavior. This is a case where testing with bad data isn't terribly instructive. Yet another reason not to use atoi.

Narue 5,707 Bad Cop Team Colleague

>How can I handle the errors in case of strtol() ?
strtol sets errno, it returns suitable values on error, and one of the parameters is a pointer that marks where the conversion stopped. You can mix and match these three error handling schemes to write a bullet-proof conversion.

Narue 5,707 Bad Cop Team Colleague

>Would you mind to elaborate in what way this would be overkill?
Gladly. I misread your post.

>here's the simple answer:
In this case I'd say that simplicity isn't worth it. You're teaching bad habits again.

>of course that doesn't even begin to address error checking.
Indeed. You make several assumptions about your data:

1) You assume that argv[1] exists.
2) You assume that argv[1] is not a null pointer.
3) You assume that argv[1] represents a valid integer.

Simple or not, those assumptions make your code severely broken because you simply can't control the data sent to your program from an outside source. At the very least you need to correct those three things:

int main ( int argc, char *argv[] )
{
  /* Make sure argv[1] exists and is not null */
  if ( argc > 1 ) {
    /* Make sure argv[1] is a valid integer */
    if ( try_parse_int ( argv[1] ) ) {
      int value = atoi ( argv[1] );

      /* ... */
    }
  }

  return 0;
}

The problem with atoi is that it's literally impossible to error check it. The return value is the only guaranteed mechanism for determining an error, and the value that atoi returns on error could also be returned on success. Not to mention that if an integer can't hold the result, the behavior is undefined. So really the only way to use atoi safely is to write or …

jephthah commented: that's actually an awesomely instructive example. beginners mightn't understand it, but i like it a lot. +1
Narue 5,707 Bad Cop Team Colleague

>how can i achieve to have the program to randomly choose a number from 0 - 27?

#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
  std::srand ( (unsigned)std::time ( 0 ) );

  int r = rand() % 28;

  std::cout<< r <<'\n';
}

Further details can be found here and here.

Narue 5,707 Bad Cop Team Colleague

strtol offers more error handling capability and is safer. atol is easier to use, but is impossible to properly check for errors and exhibits undefined behavior for some erroneous input. The basic difference is that you should use strtol unless your string has already been carefully validated and you're 100% certain that the conversion will succeed with atol.

Narue 5,707 Bad Cop Team Colleague

>Then use sscanf() to read that string into an int previously declared.
If you're already validating the string, sscanf is overkill. If it's a valid integer you can use atoi safely. Or better yet, you can combine the conversion and the validation with strtol:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main ( int argc, char *argv[] )
{
  if ( argc > 1 ) {
    long value;
    char *end;

    errno = 0;
    value = strtol ( argv[1], &end, 0 );

    if ( *end == '\0' && errno == 0 )
      printf ( "Good integer: %ld\n", value );
    else
      fputs ( "Invalid integer format\n", stderr );
  }

  return 0;
}
Narue 5,707 Bad Cop Team Colleague

>did you try this: sprintf(buff, "%ld", lval);
How does that solve the problem? The OP is converting long long int, not long int. And I've already gone through this with him, but he wants to insist that sprintf doesn't have a conversion specifier for long long even though the compiler supports the type. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

>I was just wondering if thier was a manual mathmatical way to do it?
Well, long long is just another integer type, so converting it to a string is really no different from writing your own itoa function (or lltoa, as it were). If I were you[1], I would start looking for source code to itoa variations online (of which there are many). Chances are good you can change int to long long and be ready to go. You might have to look out for range assumptions, but aside from that the conversion should be trivial.

[1] If I were me, which I am, I would write my own from scratch because I've done it before and have sufficient experience implementing libraries to trust my own skills over some random snippet I found on the web. ;)

Narue 5,707 Bad Cop Team Colleague

>I am dealing with a 64 bit value goinf to a array of
>chars and I do not see anything special for that.
Don't just look at the headers, check the documentation. I'm reasonably sure that if the compiler supports long long, it provides a format specifier for sprintf as well.

Narue 5,707 Bad Cop Team Colleague

So your compiler supports long long, but no way to format it into a string? I find that hard to believe, did you check your compiler's documentation? At the very least there should be a non-standard function or extension that supports what you want.

Narue 5,707 Bad Cop Team Colleague

>I need to understand the concept of inheritance in Oops.
>Can any one explain with real life example the use of inheritence to enhance a super class.
>It will be very helfull to me if you can explain me the use of inheritence to build a simple car.
It's actually funny how you went from a very broad question down to a very specific (somewhat unrelated) question in three sentences. Anyway:

>I need to understand the concept of inheritance in Oops.
Inheritance is nothing more than programming by extension. You take advantage of existing code by making it your own and then extending it with customizations.

>Can any one explain with real life example the use of inheritence to enhance a super class.
Okay, let's say you have a binary search tree class. Rather than re-implement all of the class framework and logistics for your new red black search tree, you can inherit the binary search tree class, re-implement only the parts that are different, and save yourself a lot of work. Also, interface compatibility falls out of this. You use the red black tree class just like the binary search tree class because they use the same interface.

>It will be very helfull to me if you can explain me the use of inheritence to build a simple car.
I'm not sure I would use inheritance to model a car.

Narue 5,707 Bad Cop Team Colleague

>Is it possible to find the variablename from Numbers[0] wich is Number2 ?
Not easily, no. The variable name is a symbol that's not available at runtime unless you store it as a string in memory. Perhaps I can give a more helpful answer if you explain what problem you're trying to solve by retrieving the variable name. Most likely I can offer an alternative approach.

Narue 5,707 Bad Cop Team Colleague

I included <algorithm> and <fstream> (because what you posted is not a complete program) and added using namespace std; . No errors, and by the looks of the error, you're using a version of Visual Studio, which is what I tested on.

Narue 5,707 Bad Cop Team Colleague

>How can I fix it so it outputs the date entered by the user when there is an error?
You're printing the value of the date itself in your error message. At that point, the date has already been checked, errored, and set to the default. Unfortunately, I can't tell you how to fix the problem without changing the Date class, because I don't know how the Date class works.

Narue 5,707 Bad Cop Team Colleague

>everytime it writes to my file it overwrites the previous data stored with in it
It sounds like you keep closing and opening the file with the ios::out mode. In write mode, the newly opened file is truncated to zero length. You can avoid that by using ios::app (as you discovered), though that effectively means you can only write to the end of the file. Another alternative is ios::in | ios::out, which doesn't truncate the file and still allows you to seek.

>is there a way to break the file up by placing an empty line
>every time my program writes to the file so its more spaced out?
Why not just do out.put ( '\n' ); after you open the file but before you write any data?

Narue 5,707 Bad Cop Team Colleague

>the segmentation fault is in the merge sort but i can tfind out how to fix it
A segmentation fault means you accessed memory beyond your boundaries. If you're using a pointer it likely means the value of the pointer is incorrect. If you're using array indexing, it likely means the value of the index is incorrect. You know the problem is in the merge sort, so the first step should be to validate the indices at every step.

Narue 5,707 Bad Cop Team Colleague

>Is this possible?
Yes, but it's not the most brilliant of ideas. What exactly are you trying to do that prompted this question?

Narue 5,707 Bad Cop Team Colleague

Post a complete (small!) program that exhibits the problem, please.

Narue 5,707 Bad Cop Team Colleague

>swap(Scores[0], Scores[min]);
>swap(Scores[1], Scores[min]);
>swap(Scores[2], Scores[min]);
>swap(Scores[3], Scores[min]);
This strikes me as a type mismatch. Most likely you're trying to swap a float with an array of floats, and the compiler doesn't like it.