grumpier 149 Posting Whiz in Training

The problem is your coding errors.

#ifndef SHIP_H
#define SHIP_H
#include<string>
#include<iostream>
using namespace std;

class Ship
{
   // stuff snipped in interest of brevity

  virtual void printInfo()
  {
    cout<<"The name of the ship is "<<name<<endl;
    endl;
    cout<<"The year the ship was built is "<<year<<endl; 
  };
#endif

"endl;" on a line by itself will trigger an error: std::endl is a stream manipulator, not something that works in its own. You have also not matched braces ({ and }). The }; on the last line ends the function body, but there is no closing of the class declaration. In subsequent code (typically within a source file that #include's this header) the compiler will get confused because things appear out of context it expects.

This is the code for the inherited class...

#include "ship.h"

#ifndef CARGOSHIP_H
#define CARGOSHIP_H

//inherits from ship.h
class cargoShip : public Ship
 
private:
int c;

{

The declaration of class members need to occur in the body of the class i.e. after the brace.

public:
   //   more stuff snipped for brevity
      //override printInfo()
      printInfo()
      {

	cout<<"The name of the ship is "<<Ship::printInfo()<<endl;
        endl;
        cout<<"The capacity of the ship is "<<capacity<<endl;
      }

You have the same coding error here as you had in your base class.

I know that I can't just call the Ship class by itself because it includes a virtual function but for some reason, when I use these two lines in my main.cpp to call the inherited cargoShip class, I …

grumpier 149 Posting Whiz in Training

There are plenty of open source C/C++ compilers. They are fairly complex bits of code, so the notion of "debugged easily" depends on your notion of what is "easy". However, the information on how they work is well documented.

If you want to debug compilers, and you have skills with that, offer your services to the development team of one of the open source compilers.

grumpier 149 Posting Whiz in Training

Oh; another tutorial on pointers is here.

grumpier 149 Posting Whiz in Training

when we use int *p=new int; we know p point to int. But i just wanna know how the compiler know p's type?

Because you've told it so. int *p tells the compiler that p is a pointer to int. The compiler also knows that the expression "new int" yields a value of type pointer to int, that can stored in the pointer p.

If you want a self-respecting compiler to complain bitterly, tell it "int *p = new double;" : it recognises that "new double" does not yield a pointer to int, and complains about a mismatch of types.

When we delete a pointer to a array, how the compiler know how many bytes to release?

The compiler doesn't. All the compiler knows is that it's asked to delete an array (as in "delete [] whatever;") because the [] tells it that.

When dynamically allocating an array, you specifically tell it how many elements to allocate. There is nothing stopping code that manages memory allocation from keeping track of things, and retrieving the value when working with the delete operator. The methods of doing that, however, vary between compilers. And there is no portable way for your code to retrieve that value (unless you also keep track of such things yourself).

grumpier 149 Posting Whiz in Training

10000000 is an integer constant, and is probably too large to be represented in the int type supported by your compiler. [That presumably means you are using 16 bit compiler].

Also, as someone said in your other thread, "if ( 4000000 < ammwater < 10000000 )" does not test if ammwater is between 4000000 and 10000000. Refer that other thread and read the explanation of that.

grumpier 149 Posting Whiz in Training

There may be a way to fool around with memory and store the information somewhere more permanent, but I don't know how to do that, nor would I recommend it.

Yeah, it's usually called "copying contents of memory to a disk file in some format" :lol:

There are some types of memory more enduring than RAM (eg ROM) but using them relies on them being present (i.e. not guaranteed to be available for use on all computers) and also relies on significantly more knowledge than saving data to a disk file.

grumpier 149 Posting Whiz in Training

All the results it gives are as if tax is zero, right?

The reason is that you're doing everything with integer arithmetic. To look at an example;

else if ( 15000 < income <= 44000)
           {
                tax = (income - 15000) * (20/100);

With integer arithmetic (20 and 100 are integers) 20/100 will be computed as 0 (integer division). (income-15000)*0 will always yield zero.

grumpier 149 Posting Whiz in Training

[1] I can't say I've succeeded, but that's my goal.

All good authors start with that goal. Very few fully achieve it, unless they simply finish off work started by someone else. The journey towards the goal, and products produced along the way, are actually what's important in the long run.

grumpier 149 Posting Whiz in Training

Not even close.

Your code does not insert any characters into the string array. What is the purpose of the "input" argument supplied to the function? where is the codes counting the number of characters read (or inserted into a string)? Where is code to make it terminate at whitespace? The length of the input string size may be arbitrary, but how does your code stop writing past the end of that length?

grumpier 149 Posting Whiz in Training

string[i]=getchar(); I might be wrong though. Feel free to correct me. :)

You're wrong. getchar() does not behave in quite the way you described. Consider yourself corrected.

Salem is right. Once you get past the concern he pointed out, there are also additional problems that the code has no error checking, nor does it terminate the input string with a zero byte.

grumpier 149 Posting Whiz in Training

The only reason this code should give you error is if you input something else that float, let's say letter [...]

scanf() would return an EOF in that case.

No it will not. It will return zero in that case.

EOF is only returned upon reaching end of input. If there is input in the stream that does not correspond to what is expected (via the format string) scanf() returns the number of fields successfully read. If there is one value to be read, and none are, the return value is zero.

Not that it matters: the return value of scanf() is not being checked.

In any event, the code that is posted is probably different from the code being compiled. And the difference is where the error is.

grumpier 149 Posting Whiz in Training

Your function highestTest() does not initialise the variable "highest", but the first operation involves comparing its value with elements of the array. That means the value it ends up with in that function will probably be junk.

The printHighest() function declares its own local variable named highest (again uninitialised so it contains junk) and prints it out.

The variable highest within printHighest() also has no relationship to the variable named highest in highestTest(): although they happen to have the same name, they are both local to the particular functions.

If you have any questions .... think first before you ask. You might be able to answer them yourself, and you will be better off if you can.

grumpier 149 Posting Whiz in Training

Only plain wrong if you're not using a compiler that has defined it. Given that that's not the case most of the time: check your compiler's documentation and see if you can use it, then, bare in mind that this code is not 100% portable and SHOULD input not work or the program simply crash you should first look at fflush(stdin);.

Yeah, right. That's like suggesting flying in a 747 with a small leak in the fuel tank .... it may seem OK at first, but the results you get in the future are better avoided in the first place.

The majority of compilers (or libraries and the targeted systems), in my experience, do not support fflush(stdin) to flush input. It just happens that one or two from large vendors do.

The more common result if fflush(stdin) doesn't work, incidentally, is not a program crash. It is usually intermittent occurrences of strange behaviours in code run after the fflush() call, with results subtly different from what is expected given previous input. Such things tend to be a nightmare to track down, because the symptoms are encountered months after the code is written.

As to the original question: it is usually a good idea to avoid mixing scanf() and getchar() calls, because of interactions like you're seeing between them. Use one or the other, and keep your code behaving consistently.

grumpier 149 Posting Whiz in Training

First tell us how you are measuring its memory usage, and the basis on which you think that usage needs to be reduced.

It would help if you used a recent compiler/library and used standard functions/etc. There is no <iostream.h> (except with old compilers) and <conio.h> is system-specific.

Memory usage of a small program like you've shown is really determined by characteristics of the compiler and its library - as are techniques to reduce memory usage.

grumpier 149 Posting Whiz in Training

As you say, Narue, my answer was what "kinda sorta" sometimes happens.

My shorter answer is the one I like for this type of question: completely accurate. But it, almost invariably, is not considered an answer to the question. Hence "kinda sorta" type answers come out of the woodwork. And standards nazis can drive a truck through the holes in such descriptions ;)

grumpier 149 Posting Whiz in Training

This is off-topic in a C++ forum.

However, I'll take pity and offer suggestions. No guarantees though .....

1) Check if you have a hardware problem: for example a loose memory module, a loose connector, a card that's loose in its slot. Loose bits of hardware can cause all sorts of strange and intermittent symptoms: rebooting without notice, blue screens of death under windows, strange application errors. You might also have a device nearing its end of useful life (eg a dying hard drive).

2) You may have also have screwed up your windows installation (solution: backup all data you care for, and then reformat your hard drive and reinstall your operating system and applications from scratch).

grumpier 149 Posting Whiz in Training

The short answer: wherever the compiler and/or system choose to store them.

A longer answer follows.

Older systems used to make a distinction between "stack" and "heap" (e.g older IBM compatible PCs used different memory chips for "stack" and "heap", and needed special drivers to access heap). Global, static, and local variables were often stored in the stack, and dynamically allocated objects (eg created with malloc()) were often created in the heap.

These days, with modern 32 bit and 64 bit operating systems, there is no real distinction between "stack" and "heap". Accordingly, variables are stored in whatever memory makes sense.

Register variables are, in general terms, stored in machine registers. However machine registers are a relatively scarce resource, so compilers are smart in how they use them. So, if the register keyword is used in C/C++, the compiler may choose to ignore it, and allocate the variable like any other.

grumpier 149 Posting Whiz in Training

It is because you are assigning the value to argv[1] every time in your if condition. Use == instead of =

Wrong. As Dave said, comparison of char arrays (aka "C style strings") should usually use strcmp() rather than ==.

grumpier 149 Posting Whiz in Training

The simpler way (less error prone) is to use a typedef helper.

typedef float ((*YourFunction)(int, int);
   YourFunction YourArray[3];

or, if you wish code that is terse but easier to get wrong (typos very easy), use this;

float (*YourArrayAlternative[3])(int, int);

to declare an array named YourArrayAlternative.

Whichever way you choose to do it, I'll leave it to you to work out how to initialise array elements.

grumpier 149 Posting Whiz in Training

Yes. Look up the C standard header stdarg.h or (in C++) the standard header <cstdarg>. Those headers contain macros and types that support writing functions with variable argument lists.

grumpier 149 Posting Whiz in Training

Apart from that, it often takes a lot more effort to write assembly code to achieve X than it does to do X in a higher level language like C. C also has a library .... which means it is not necessary to code everything from scratch.

As an exercise, try getting to the stage where you have some level of familiarity with both assembler (on your target machine) and with C. Then pick a reasonably non-trivial programming task that seeks to read data from files, do some processing, and write data back to files. First implement it in assembler, and track how long it takes. Take a week off to clear your head. Then implement it in C, (without looking at any of the design or code from your assembler work) and track how long that takes.

When you've done that, report back here (I'll look forward to seeing your post in a couple of months).

Odds are, you will find things take you a lot longer with assembler.

grumpier 149 Posting Whiz in Training

Yes, but does he want to compare test with '1' or with 1? Because that's different thing!

Ah, yes. Good point. Something for the original poster to contemplate .....

grumpier 149 Posting Whiz in Training

It still won't work. You are comparing char with int:
getBinary is char, and 1 is int.
char != int!!!

It will work. Comparing char with int is allowed.

Worst case is a compiler warning (eg mismatch of precision of operands). A compiler warning means the programmer should check and make sure the code has the intended result, not that it is disallowed.

grumpier 149 Posting Whiz in Training

You're the one who provided partial code with a description "goes something like this", and then didn't explain why the output you get does not correspond to the input.

I fail to see how your input;

GREEN HOME 2
GREEN START 4
RED HOME 17
RED START 19
BLUE HOME 32
BLUE START 34
YELLOW HOME 47
YELLOW START 49

should not yield the output you're getting (with your comments from your original post).

0 <- Player Number
GREEN 2 <- This should be Blue, not Green
GREEN 4
1 <- Player Number
RED 17
RED 19
2 <- Player Number
BLUE 32
BLUE 34
3 <- Player Number
YELLOW 47
YELLOW 49

It seems logical to me that your code - incomplete as it is - and an input file with first line "GREEN HOME 2" and second line "GREEN START 4" would yield output of "GREEN 2" followed by "GREEN 4". However you expect the first line of output (for player 0) to be "BLUE 2".

If the rules of the game suggest that, then fine. But you have not shown any code that would make that happen.

grumpier 149 Posting Whiz in Training

My code goes something like this:

Try giving a small but complete sample of actual code that illustrates your problem, rather than "something like this" which may actually be different. Include a sample input file as well.

At the moment, we can't guess the cause of your problem as you are describing what you think the code does and what it is doing wrong. Whereas the actual problem is in actual code that behaves differently from your expectations when given an input file that you haven not shown here.

grumpier 149 Posting Whiz in Training

1) Comparison of test with 1 has two equals signs, not 1 if (test == 1) . Having one equals sign assigns test to 1.

2) main() returns int, not void. Wash your mouth out with soap for returning void.

grumpier 149 Posting Whiz in Training

Not quite. It is quite legitimate to do this;

void func(float aName);   // declaration (which may come from an #include'd header)

void func(float AnotherName)
{
     std::cout << AnotherName << '\n';
}

In other words, the argument name in a function declaration is not required to match the argument name in the function definition (ie implementation).

grumpier 149 Posting Whiz in Training

As a matter of fact, no.

The name of an argument in a function declaration (ie. "myFloat" in void foo(float myFloat); ) is generally ignored by the compiler. It is generally used simply to give information to the programmer (eg by providing a descriptive name, rather than adding an additional comment). That argument name has no relationship to any variable within the caller (eg in main()).

grumpier 149 Posting Whiz in Training

The short answer is "yes and no".

The C++ standard specifies no direct means of accessing hardware. However, with the help of non-standard techniques (which are operating system and hardware specific) it is possible to control hardware. Technically, those techniques are beyond scope of the C++ standard but, in practice, with support of suitable compilers and their libraries it is possible to find ways ....

grumpier 149 Posting Whiz in Training

You seem to have solved the looping problem, except that in most tests a grade of zero is possible and your (grade > 0) condition excludes that.

An aside: I knew a teacher who came up with a test that, she said, nobody could earn a zero grade .... because there was one mark for candidates spelling their name correctly. One of her students mispelt his name.

grumpier 149 Posting Whiz in Training

Salem is right; there is no way to #define a macro that expands to a preprocessor directive.

There is also the incidental concern that #warning is not a standard preprocessor directive.

Any C++ compiler will generate an error on an attempt to call a function that has not previously been declared.

I can't see the point of what you're trying to do. If <window.h> is not included

#ifndef _WINDOWS_H
#error <windows.h> needs to be included to compile this source file
#endif

will generate an error message that gives specific information on requirements.

Of course, if you need to use the above (eg if you have a header that relies on <windows.h>) it would be easier to #include <windows.h> anyway

grumpier 149 Posting Whiz in Training

x is not initialised to point at anything and you are dereferencing *(x+i*nc+j) in your loops.

Before your loops, you need to make x point at something valid, such as the first element of an array with nr*nc elements.

grumpier 149 Posting Whiz in Training

A professional uses whatever methods are appropriate for the task at hand; if a task that's outside his/her experience comes up, then a professional will investigate and find an appropriate method. If the first method doesn't work quite right (eg doesn't meet the key user requirements) then a professional will look for alternate methods.

grumpier 149 Posting Whiz in Training

cin waits till the user enters the answer... but is there any input method which wont wait for the user?

Neither standard C not C++ support such a capability (over-simplistically, because C and C++ are designed to work on platforms without a keyboard, and such capabilities generally amount to reading keystrokes directly from a keyboard).

To do this, you will need to read the documentation for your operating system and non-standard library features supported with your compiler.

grumpier 149 Posting Whiz in Training

as for finding the the other 'exact' topic. i found it, some time ago and it did me no good which is why i made my own post.

Well, you get nothing further from me. That thread contains all the information you need. It doesn't give a canned answer though: you need to put in a little effort rather than relying on spoon-feeding.

grumpier 149 Posting Whiz in Training

Instead of

while ( !indata.eof() ) 
{
    indata >> EmployeeInfo[employee_count].set_first_name();
    cout << EmployeeInfo[employee_count].get_first_name(); 
    // etc
}

try doing this;

string temp;
while ( !indata.eof() && employee_count < MAX_EMPLOYEE_SIZE) 
{
    indata >> temp;
    EmployeeInfo[employee_count].set_first_name(temp);
    cout << EmployeeInfo[employee_count].get_first_name(); 
    // etc
}

The additional check of employee_count stops running off the end of the array.

It is often a poor idea to use a float or double to represent currency figures. Particularly things like using 27.12 to represent $27 and 12 cents, as a floating point variable cannot represent 0.10 or 0.01 (or most combinations thereof) exactly. If you're only going to work with currencies that are dollars and cents, use a struct that represents the dollars and cents as separate fields, and manage the entries accordingly.

grumpier 149 Posting Whiz in Training

For information on the help you can expect here with homework problems, have a look here.

If you have a further look through the forums, there was a thread on your exact topic (more precisely, a discussion of how to evaluate that particular summation) a week or so back. However, you need to do some work for yourself, so I'll leave finding that thread as as something for you to do.

grumpier 149 Posting Whiz in Training

You are passing arr, an array of length 3 to the function, and returning arr[5].

arr[5] does not exist, as far as your program is concerned. The array does not get resized. In fact, by doing this (accessing the value of something that does not exist) your program is exhibiting undefined behaviour.

The term "undefined" in the C and C++ standards has (ironically enough) a specific meaning. It means that, as far as the standard is concerned, the results from running your program can be anything. The function might print a value of zero. It could also (conceivably) reformat your hard disk. Given that these and many other possibilities are allowed, the message is: don't write or run code like this.

If you change your line in main() to;

cout<<func(arr[10]);

the compiler will generally complain. arr is an array of integer. arr[10] is the value of the 11th element of that array (which doesn't exist either, so accessing it also causes undefined behaviour - refer above). Either way, an element of an array and the array are different things: in C++, they show up as having different types, and passing something of type A to a function that expects an argument of a completely different type B is not allowed.

grumpier 149 Posting Whiz in Training

When you install Dev-C++, at some point you need to specify a directory where it gets installed. Whenever you (or a batch script you're executing) refers to D:\gcc, you need to change it so it refers to the directory you installed dev-C++.

If you did install into d:\gcc, then presumably you or someone else have removed that directory. So you need to reinstall dev-c++.

grumpier 149 Posting Whiz in Training

When you append pointers onto a vector of char, the pointer is copied. You are expecting the data the pointer points at to be copied.

With a vector<char *> you need to explicitly copy the data as well as the pointer.

An easier way would be to use a std::vector<std::string> instead (as std::string objects copy the data implicitly).

grumpier 149 Posting Whiz in Training

More specifically, a small piece of code that actually exhibits the behaviour you consider to be a problem.

The code you've given does not appear related to the text in your post in any way.

grumpier 149 Posting Whiz in Training

Or did you just retype the code here based on what you thought you have (which would be worse than useless) ?

Yeah, I noticed that too. I assumed the post was just typing what she remembered having, as the code could never compile, so just focused on "uninitialised variables yield crap results, even if code is otherwise correct". Cumulatively, a combination of the types of errors Salem and I have pointed out would explain what's happening.

grumpier 149 Posting Whiz in Training

There is also the incidental concern that your function is recursive, which does not meet the requirement to be non-recursive.

grumpier 149 Posting Whiz in Training

You have not initialised min, ret, cent, or invalid, which means their starting values are undefined (ie can contain random junk). Then, in your loop, you increment them. You then add the resultant values to compute total .....

Starting with junk values and incrementing yields more junk. Adding junk values yields further junk

Also, before you ask other questions in this forum, have a look at this message. In particular, note the need to use code tags, in order to format code in a way that is human readable.

grumpier 149 Posting Whiz in Training

I'd say you've got Buckley's chance of finding someone here who will do your homework for you.

grumpier 149 Posting Whiz in Training

A c-style string (eg a string literal) is an array of char that, by convention, is terminated with '\0'.

grumpier 149 Posting Whiz in Training

Heaps of things wrong with your code.

1) You need to decide if you are working with a 1D or 2D data structure.

2) You need to decide whether your copy constructor does a deep copy (i.e. dynamically allocating rows and columns, and then copying all the values). At the moment you're doing (sort-of) a shallow copy - which means that a copy of a matrix shares memory (and therefore data) with the original. That means changing one Matrix will change the other.

3) your operator<< outputs values of pointers (value[j] is of type pointer to int). It is not outputting the actual data stored in the matrix. The only way reading in will work again is if your program does not change those pointers. You are essentially relying on your data to be hard-coded into your program if you read in pointer values.

4) As a general rule, the logic of an istream extraction operator (>>) should be the reverse of the ostream insertion operator (<<). In other words, if your operator<< outputs X, Y, and Z in that order, your operator>> should attempt to read X, Y, and Z in the same order.

If you don't understand the above comments, start with something simpler: like a 1-D array. Work to understand that first, before you try to work with a 2-D matrix.

grumpier 149 Posting Whiz in Training

So, my query is, why this is happening only in case of strings and not for the others( like int, float, single character)?

Because the %s format specifier tells printf() and related function that the corresponding argument is a pointer to char and to keep printing chars until it finds a zero.

When an array is passed to a function (be it array of char, double, or structs) only a pointer to the first element is passed. No information about the number of elements in the array is passed. So the function has to use some convention (as printf() does with the %s specifier) or make an assumption (eg it assumes the array is of length 5).

grumpier 149 Posting Whiz in Training

The first error message is referring to std::size_t and (presumably) std::ptrdiff_t types not being declared. You need to #include standard headers that declare them.

Other messages are telling you about the need to add "typename" to some of your declarations (presumably typedefs).

Your header - at least the way you've shown it - only declares constructors (and various other member functions of your class), and does not implement them.

Taken literally, the error messages you've shown are indicating a problem with comments (eg an error reported for line 31, but line 31 is commented out) Which suggests those error messages do not correspond to the header file you've provided.

Your list of error messages also has atypical characters in it (eg ‘) which makes the messages hard to read.

Accordingly, I gave up on trying to make more sense of your problem.

grumpier 149 Posting Whiz in Training

Hi,
But, when we define any character array as
char a[3]={'a','b'};
then compiler here automatically consider '\0' null character to represent the end of the string

That's not true. You have explicitly initialised two elements of three-element array. The standards go about it in a round-about way (there's a logic train to follow to get to the conclusion, and the C and C++ standards have different logic trains) but the end result is that a[2] in your example will get a value of zero.

You will get the same effect (other than type of elements) with

int a[3] = {1, 2};

ie a[2] will get the value of zero.


So, my question here is:
As compiler do not needs to use any such terminator to indicate that the int array or float array is terminated. Then, why compiler needs to assign '\0' null terminator in char array & why not in others?

It doesn't. If the number of explicitly initialised elements of an array is less that the size of the array, the standards specify how the other elements are initialised.

There is an anomaly in C (and C++) that allows char arrays to be initialised using strings (and arrays of wchar_t to be initialised with wide strings). Strings, by convention, are zero terminated. There is no equivalent to this style of initialisation for other types. But this anomaly is a different thing from what you're asking about.