while("sMessage[x]"){
Why quotes?! ;)
It's a loop forever: while (pointer to string literal != 0). It never is null...
while("sMessage[x]"){
Why quotes?! ;)
It's a loop forever: while (pointer to string literal != 0). It never is null...
About the second point. I think that error message printing on too low level is a very harmful practice. In that case we have a chance to get a bucket of messages on a single failure. Besides that low level routines can't print sensible messages because they have no wide context info. For example, the only sqrt calculation routine message is "Alas, my argument is lesser than zero" - well, it can't be helped. Now you can't use this damned routine in GUI codes - std::cerr object does not exist there...
I'm not sure that exception on open file operation failed is a good idea (of course, it depends on developed system architecture). As usually we don't open files in every line of code. It's not so hard to check return code from loadFile routine (file is loaded or not loaded). Exceptions are suitable for extraordinary, as usually fatal (global) events. Yet another example of local failures where exceptions are suitable: get next token calls in syntax parsers (or get next CSV field in data importers). We can avoid annoying return code checks if getnexttoken will raise an exception if no token or bad token detected. We'll catch this exception locally, make recovery, print sensible message etc.
;)
bool isEven(const char* number)
{
bool even = false;
if (number) {
if (*number == '-' || *number == '+')
number++;
if (*number) {
even = true;
do switch (*number++) {
case '1': case '3': case '5': case '7': case '9':
even = !even;
continue;
case '0': case '2': case '4': case '6': case '8':
continue;
default: return false; // not a number
} while (*number);
}
}
return even;
}
inline
bool isEven(const std::string& number) {
return isEven(number.c_str());
}
/// for true integers:
bool isEven(unsigned long number)
{
std::string buff;
std::ostringstream is(buff);
(is << number).flush();
return isEven(buff);
}
using std::cout;
using std::cin;
void TestEven()
{
std::string line;
while (cout << "Integer: ",std::getline(cin,line))
cout << isEven(line) << '\n';
}
1. Use code tag correctly:
[code=c] source
[/code]
2. Have you ever heard that all names must be declared before used in C? If not, take your textbook again. If yes, what's str (or str2) in strcat385 body?
3. What's an index of string2 element in string1[i] = strign2[];
? Can you explain what is it: while(str2[])
?
4. I see that strcat385 must return a pointer. Where is return statement in this function body?
It's hard to say that absolutely senseless and untidy text demonstrates your efforts...
The _beginthread first parameter is a pointer to an ordinar function, not a pointer to member function. There are two absolutely different sorts of pointers in C++.
See, for example: http://www.goingware.com/tips/member-pointers.html
It's not only the most slow algorithm (the original one) but it's a wrong algorithm. You have got not a sum of digits but a sum of char codes of digits. It's the other story that char code of '0' is even numbert in ASCII table; the C language does not specify this fact.
It's so easy to get the last digit of integer n: n%10
then get the last digit of n /= 10
and so on...
Lines to be read: end - start + 1
Pointers allocated: end - start
Did you understand?
Use code tag with the language specifier!!!
[code=c] sources
[/code]
Always check program arguments: argc == 4 then start > 0 and start <= end.
NEVER use float data type in math and financial calculations, it has too low precision. Standard C and C++ floating point type is double (have a look at <cmath> header contents).
Use modf library function to separate integer and fractional parts.
1. Use code tag correctly:
[code=cplusplus] source(s)
[/code]
2. You forgot to initialize listData in operator=()
3. You forgot to delete old list in operator=()
4. You forgot to check if (this != &anotherList)
in operator=()
5. Use listDate or topPtr to point to the list head, not both
...
Try to correct the code then come back ;)...
Did you mean constructor with 'ctor' ?
Of course, ctor is a common abbreviation for constructor (and dtor for destructor) in C++ context. But this syntactical construct named exactly as ctor-initializer in the C++ Standard.
See also http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/
A type (a class) is a set of values + a set of operations. Strictly speaking, a (linked) list is not a simple collection of nodes. It's a collection of values (data) with operators:
- first (or head, or front)
- last (or tail, or back)
- count (or size)
- append (or add, or push_back)
- insert (optional)
- erase
- clear
- next
- prev (optional)
- find
- swap (optional)
- sort (optional)
and so on...
Look at http://en.wikipedia.org/wiki/Linked_lists.
Read about STL list container as an example of true class list.
As usually, a list implementation is a chained (by pointers) collection of nodes. A list node is a term for a value plus internal (as usually, invisible for list users) reference field(s) data structure.
Of course, you may define specialized class list of public nodes with exposed auxiliary next/prev fields. Remember: class list user don't want to take much trouble over these pointer fields. Moreover, it a very dangerous approach (how about unpredictable change of reference fields by wrong user code? ). It's class list member functions job.
A pointer value will never been "deleted" automatically. The life span of the state pointer variable does not bear a relation to the life span of the referred object.
In other words, a pointer is a road sign only: "that's a road to Pompeii". May be, the Pompeii was strewn with Vesuvias volcano eruption ashes...
All about pointers for newcomers (and all others ;)):
http://eternallyconfuzzled.com/tuts/languages/jsw_tut_pointers.aspx
Don't stop C++ programs with exit() function (except on severy run-time errors).
Use return exit_code_value;
in the main.
>Here is the shortest code for finding the fibo series
I think this code is shorter, don't you?
void Fib(int fmax)
{
int i = 1, f[2] = { 0, 1 };
while (f[i] < fmax) {
cout << f[!i] << '\n';
f[i^=1] = *f + f[1];
}
}
;)
A classical case. Only base class destructor called because your BaseFoo is not a polymorphic class. It can't deallocate any vectors in the derived class: it knows nothing about its descendants.
Make it as a polymorphic class (fortunately, it's so simple) and see what happens:
class BaseFoo {
public:
BaseFoo() {}
virtual ~BaseFoo() {}
};
stdio.h is used in vc6.0 and many other old programs.
in VC2008 you use
#include "stdio"
????
Impossible!
No such header as <stdio> (especially "stdio" ).
Standard C stream i/o header is <stdio.h>. In C++ you may include it as <cstdio> - that's all...
It looks like a blind man told to a deaf man about colors ;)
>a misfortune happened, here unmaybe I in any way to complete work for a bank...
Now I see why the Current::WorldFinancialCrisis happened :(
Are you sure that these project "specification" are complete?
;)
Read more:
http://www.daniweb.com/forums/announcement8-2.html
>I'm limited as to what I can give you (security reasons)
Hehe, the Top Secret Addendum to the C++ Language ;)
It seems nobody can tell you anything with unknown types of state.Variable and saveloadtypes array or strTmp and strBuf scopes or correct pFrame and m_pAppWnd pointer values...
There are lots of possibilities to get troubles in this code snippet.
Regrettably I can't enumerate all ones here (security reasons)...
1. Move all function definitions to a separate .cpp file (and never, ever include them in .h files, except class templates - but it's the other story).
2. Think about month[i] = !month[i]
Some melancholy remarks:
The most serious defect of strtok-based CSV parsing is that strtok skips null values. For example, in the line "1st,,3rd," strtok selects only two tokens: 1st and 3rd.
In practice most of CSV exporters (DBMS especially) write this line for four data fields tuple (record) with null 2nd and 4th values, not for two-fields. Obviously, strtok-based parsing keeps silent with wrong result for this line.
Besides that a strtok-based CSV parser can't process quoted text CSV data fields.
Regrettably, an adequate CSV parser is not a 3-5 source lines function :(
Fortunately, it's not so hard to write a good CSV parser ;)
About common CSV specifications see:
http://en.wikipedia.org/wiki/Comma-separated_values
My 2 ( may be 3 ) cents:
Look at:
http://en.wikipedia.org/wiki/Matrix_square_root
http://www.newton.dep.anl.gov/askasci/math99/math99208.htm
See also an interesting discussion on the topic:
http://yarchive.net/comp/sqrtm.html
Show me the code you have, and I can see what help I can offer once I see what effort you have applied.
Step 1. Read argv[0]. argv[0] is the name of the file
Step 2. Check that argv[0] file still exists (yeah, it should)
step 3. Open the file pointed at by argv[0]
step 4. Read the file, and display it to the screen.
step 5. Close the file, and end the program.
Yes, it's a good joke: to print its own EXECUTABLE module. But the most funny thing: argv[0] IS NOT an executable file path. It's a name of a program (if it's accessible). For example, VC++ release mode executable module started from (for example) d:\myproject\prog.exe has "prog" as argv[0]
argument. Of course, you can't "open the file pointed at by argv[0]
" in such a case ;)...
#include <iostream>
using namespace std;
struct deneme
{
int a;
void (* myFunction)(int a);
void look4adventures() { myFunction(a); }
};
void function1(int a)
{
cout << a << endl;
}
void function2(int a)
{
cout << a + a << endl;
}
int main()
{
deneme myDeneme[] = {{1,function1},{2,function2}};
myDeneme[0].look4adventures();
myDeneme[1].look4adventures();
return 0;
}
Honestly speaking, I can't understand your true problem. It seems no need in function pointers in your code at all. For example, xSquared member function does not bear a relation to the class Int, it does not use any class members. Evidently, it's an ordinar function: double sqr(double x) { return x*x; }
(never use expensive pow function if you have the simplest expression ;)). Useful member functions of Int object like xSquared must have no arguments...
Pointers to member functions and pointers to ordinar functions are totally different beasts. Look at this code (it works ;)):
#include <cmath>
#include <iostream>
double square(double x) { return x*x; }
class Int
{
public:
Int(int x = 0):i(x) {}
double square() const { return (double)i*i; }
double cube() const { return square()*i; }
double sqrt() const { return ::sqrt((double)i); }
double mult4(double (*f)(double x)) {
return 4.0*f((double)i);
}
double mult4(double (Int::*f)()const) {
return 4.0*(this->*f)();
}
operator int() const { return i; }
Int& operator=(int x) { i = (x>0?x:0); return *this; }
private:
int i;
};
const char eol('\n');
int main()
{
Int two(2);
std::cout
<< two.mult4(square) << eol
<< two.mult4(&Int::square) << eol
<< two.mult4(&Int::cube) << eol
<< two.mult4(sqrt) << eol
<< two.mult4(&Int::sqrt)
<< std::endl;
return 0;
}
See also:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
http://www.goingware.com/tips/member-pointers.html
http://www.newty.de/fpt/fpt.html
The order of evaluation of operands of the operator << is unspecified by the C++ Standard. Therefore both cases in the original snippet are ill-formed. It's another case of the famous bad code example a[i] = ++i;
;)
The order of operands evaluation (from left to right) is defined for comma operator, operator && and operator || only...
Quick pointer answer: you DON'T DEFINE ptr pointer variable but use it.
int *ptr; // Now ptr has a garbage value (points to nowhere)
int var;
ptr = &var; // Now ptr points to var.
*ptr = 5; // Now var has value 5.
May be your VC++ 6.0 installation was not patched properly (upto Service Pack 6 or 5, I don't remember now). In actual fact there were errors in VC++ 6.0 but as usually I have found some workarounds...
Apropos, a possible reason of the strange output:
printf("%f\t%f\t%f\t%f\n",m_Length,m_Width,m_Height,volume);
// () missed after volume
It's impossible to detect this error in compile time. That's why awkward C++ streams are better than old good printf ;)
I must say I always love a program where I can use #include<vector> vectors are like the peanut butter to my chocolate!
Well, start all your modules from
#include <vector>
using std::vector;
Who knows what may happen below ;)...
An IDE (Integrated Development Environment ~= text editor+compiler+code browser+linker+debugger etc bears no relation to the desired functionality.
There are lots of methods to do that (besides OS-specific connections of program console i/o to the remote terminal client). For example, you may write your program as CGI (or better FastCGI) requests handler. Probably, the most expressive way to go: make your program as http server. Have a look at dlib library:
http://dclib.sourceforge.net/
See http server example: http://dclib.sourceforge.net/server_http_ex.cpp.html
Some tens of lines - and your C++ console program turns into the real web-server ;)
The std::vector::at
member function is not identical to std::vector::operator[]
, use (*PtrMyVector)[i]
. In actual fact better pass vector by reference:
void ReadMyVector(vector <int>& PtrMyVector);
There is something that I saw and wanted to check if it is really wrong, as I thought. In the second edition of The C Programming Language 2nd ED by Brian Kernighan and Denis Ritchie, in the section of 5.2 Complicated Declarations, in page 109, it is written so, isn't it false?
char **argv
argv: pointer to char
Isn't it pointer to char* or pointer to pointer of char?
K&R, chapter 5:
Since argv is a pointer to an array of pointers...
...argv, which is a pointer to pointer to char...
Where is "argv: pointer to char" in K&R?
It's not an "old compiler" issue, it's normal behaviour for floating point data calculations. You have not the right to an "exact" result for these calculations. Only integral numerical types get "exact' results. The "obscure" value -5.77338e-017 is a good approximation for least valued bits of double type mantissa. Now remember that 0.9 and 0.96 numbers (periodical binary fractions) have no exact double representation at all...
1. That's because the modification (improvement) of getSmallest and getLargest functions was incorrect. It was wrong solution to assign a role of for loop counter to output parameter count (why "count" if it's an index of? ). Think: the 1st count value is 1 (must be 0) and the last is 12 (then you add 1 and print 13). Make obvious correction.
2. Look again to getAverage code: it's WRONG!!!
Ooh, that's right code:
double getAverage(double array[], int size)
{
return getTotal(array,size) / size;
}
Hi
I have include a header file in my main file.
That header file contains the function getPath
But still I am getting this error
error C3861: 'getPath': identifier not found
Even I have written the prototype of the function.
Regards
Karan
Hi.
Accept my condolences.
And what's your question?
What's a problem?
class A {
public:
A() {}
explicit A(const std::string& n):name(n) {}
const std::string& getName() const {
return name;
}
protected:
std::string name;
};
inline
std::ostream& operator<<(std::ostream& os,const A& a) {
os << a.getName();
return os;
}
class B: public A {
public:
B():A() {}
explicit B(const std::string& n):A(n) {}
};
inline
std::ostream& operator<<(std::ostream& os,const B& b) {
return operator<<(os,static_cast<const A&>(b));
};
void abtest()
{
B dude("mbayabo");
std::cout << dude << std::endl;
}
inline
char* Min(char* a, char* b, char* c) {
return
strcmp(a,b) < 0
? strcmp(a,c) < 0? a: c
: strcmp(b,c) < 0? b: c;
}
;)
2) Nothing I disagree with, but I tried making a simpler example for the OP to follow.
Yes, I understand. But let's look dangers in the face ;): a novice can confuse reference and pointer (different) concepts. Let Java community go that way. Thank God we are C++ people ;)...
1. Try to profile subset generator without any printing. There are ~1 million subsets (2^20) for N==20. To print 1 million lines... The program PRINTS all the time.
2. NextSubset code is obviously wrong: while(!Bitmask[i]&&i>=0)
refers to Bitmask[-1] at the last loop. Present all class Subset definition.
You calculate n! instead of x^n (see num calculation in the loop).
Think about less expensive calculation of the next series members...
The template generation does not pay attention to executable statements in the template definition. The if (n > 0)
does not prevent recursive template bootstapping for GetNRands<0>, GetNRands<-1>
and so on. It's pity that VC++ can't detect this "instantiate forever" recursion.
To break this recursion you may define this template specialization for n = 0:
template <>
struct GetNRands<0> {
static void fillVector( set<int>& v, int max ){}
};
It's a template generation analogue of sacramental if (n == 0) return 1;
in famous (and the same absurd) recursive factorial ;)
Have you ever seen the compiler message? It's AdjacencyMatrix constructor was not defined!
Keep it simpler, it's C++ now and here: ;)
#include <ctime>
#include <cstdlib>
#include <algorithm>
...
srand((unsigned)time(0));
random_shuffle(deck,deck+52);
// All done ;)
You guyz talk to much..She just want the codes..So!!...
Probably but I'm here to give fishing-rods, not a fried fish ;)
typedef char Name[41];
Name* name = new Name[501];
...
delete [] name;
Is it so hard job to correct obvious errors: you get compiler messages on wrong function arguments: fread and fwrite want POINTERS to target/source data areas (&d - not d, &b - not b))!
Use code tag properly:
[code=c] source
[/code]
Never use dangerous gets function: it does not check target buffer size. Use fgets instead of gets:
fgets(fn,sizeof fn,sdtin);
With gets you program crashed if the file name length is greater than 49.
Don't forget to append carriage return:
printf("\nFile saved\n");
Avoid using of non-standard function flushall().
and my tutor did say i can use gets or fgets so i dont know why he said it
May be he is an inclined to sadism person. If so and if you are a latent masochist then use gets...
;)
Of course, all good C++ implementations "prevent modification for chars that are const". All char literals placed in read-only address subspace. The C++ Standard forbid to modify text literals. However it's possible (but illegal) in old DOS implementations (BC++, for example): no hardware support for read-only memory in DOS.
char str1[] = "Hello";
char* str2 = str1;
It's totally different case: ordinar char array is defined. You can modify its contents.
Yet another tip about pointers to C-string literals in C++:
const char* p1 = "Hello";
const char* p2 = "Hello";
cout << (p1==p2? "Yes" : "No!") << endl;
This program may print Yes or No! - both cases are correct! The second occurence of "Hello" literal may denote the same or different memory address. It's an implementation-defined issue.
Regrettably, this very strange operator+= overloading is legal in C++.
Present the code fragment where these errors were detected. I'm sure it's wrong code fragment incorrectly used the 1st overloaded operator.
What's a problem? Do not declare this static member array as const - that's all.
At first YOU say to compiler that "it's a constant array, don't allow ME to change it" - then cry ;)...