>> Here is the same code similar to the C code in C++ to save you the bother.
>> Thread Solved.
Sorry, but I think you should Read This Before Posting .. scroll down to the "Don't give away code!" section.
>> Here is the same code similar to the C code in C++ to save you the bother.
>> Thread Solved.
Sorry, but I think you should Read This Before Posting .. scroll down to the "Don't give away code!" section.
>> Error 1 - error C2011: 'Controller' : 'class' type redefinition 9
An unfortunate space character has slipped in, preventing the definition of the intended CONTROLLER_H
macro ..
Controller.h
#ifndef CONTROLLER_H
// #define CONTROLLER _H // <--- wrong
#define CONTROLLER_H // <--- right
#include "LevelFolders.h"
...
Good grief .. how come vijayan121's post ^^^ goes so unnoticed here?
>> .. I have already defined pluginList but errors errors errors
>> Below is full error log ..
Hmm, the errors seem mostly pretty trivial (e.g. missing #includes, scope resolution ( std::
) and function arguments).
So I suggest that you work through the error list (from top to bottom). Try solving one error at a time, then re-compile and see what is the output.
;)
PS.
This is not C++
double [] retVal;
This would be ..
double retVal[ <some const size here> ];
[EDIT]
Regarding this "double retVal[]", it is an array local to the function - so you must not return an address to it, because it's garbage as soon as the function returns. You need to re-think that one.
>> ... Obviously it doesn't work ...
Please see Narue's Read This Before Posting, mostly the "Describe your problem clearly and fully!" section.
Explicitly returning a value from main() should not be necessary, the standard says:
If control reaches the end of main without encountering a return statement, the effect is that of executing
return 0;
>> To indicate success back to the kernel, you should return 0, or non-zero if there has been some kind of catastrophic failure ^^
The two pre-defined macros EXIT_SUCCESS and EXIT_FAILURE (from <cstdlib>) can also be used.
At least the stats
constructor needs some attention, see the comments below.
<snip>
while(i<(d_data->nCols*d_data->nRows)){
d_data->data[i]=datap->data[i];
// 'i' gets incremented too early here
i++;
// Upon last iteration; i == d_data->nCols*d_data->nRows, which is wrong
uchar n = datap->data[i];
// .. then, the damage is done here ...
d_data->data[i]=n;
uchar m = d_data->data[i];
}
Looks like nbaztec and jonsca sorted your problems out.
However, I'd like to point out a basic thing that you've been doing wrong, namely "number_of_users = ++number_of_users".
Do not write code like that, see comp.lang.c FAQ list ยท Question 3.3
I trying to get the LAST modified
Then you want to use ftLastWriteTime
.
to decide which text file is the most recent
You can directly compare the FILETIMEs using CompareFileTime()
Your ifstream is in a fail state once you have exited the loop.
To make the stream functional again, use clear(), like so..
// Clear out any error state bits
in.clear();
// Now seekg() will work
in.seekg(0, ios_base::beg);
Then, don't use .eof() in a loop control, it will end up biting you.
There are many discussions at DaniWeb and elsewhere about why it is bad.
Instead, you could read from the file as follows ..
// Loop while reading of two values succeeds ..
while(in >> code >> amount)
{
if (amount > N)
records++;
}
// Was the whole file read?
if(in.eof() == false)
{
// No, do something ...
}
To understand this better, modify your input file so that it contains non-numeric data and watch how your current program enters an infinite loop, for example:
1213 2232
4324 gotcha
432 34233
argument of type "const char *" is incompatible with parameter of type "LPCWSTR"
See this codeproject article What are TCHAR, WCHAR, LPSTR, LPWSTR, LPCTSTR etc?
Just a suggestion in case this ICODE button re-appears.
Would it be possible to display it as e.g. "INLINE", instead of the previous "ICODE"? I think that would cut down the number of posts with code snippets encased in ICODE tags (there are lots of those).
is giving segmentation error when reaching the fprintf() function ......
You have a really nasty bug there, something is wrong with the following line ..
...
if(logs = NULL)
...
Furthermore, if you fail to open the log file, then you must NOT try to fprintf() anything to it (otherwise, the result is the same as now - a crash).
PS. Have you checked that the compiler is not giving any warnings?
the call stack has following values.
fwrite(const void * 0x0012ee5c, unsigned int 0x00000001, unsigned int 0x00001000, _iobuf * 0xffffffff) line 105 + 3 bytes
The last parameter for fwrite() has an invalid value (0xffffffff).
Make sure that you succeed in opening the file properly (using fopen()), like so ..
FILE * fp = fopen("my_file.txt", "w");
if(fp != NULL)
{
/* Managed to open it, now write ... */
fwrite(..., fp);
}
PS. Why is your text all in bold?
Gives this error
undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Complex const&)'
This occurs because the Complex &
is const
- and you try to use non-const
methods on the Complex
object.
By making the methods const
, your current code will work, like so ..
class Complex{
...
int getRe() const {
...
int getIm() const {
...
friend ostream & operator << (ostream &, const Complex &);
};
Furthermore, since the operator overload is friend, you can directly access the member variables (no need to call the methods), like so ..
os << "re:" << it.re << " im:" << it.im << "| " << endl;
Regarding usage of const
, I'd suggest that you read about const correctness.
It's throwing #234 - More data is available.
Alright, this is progress.
See RegQueryValueEx documentation about its last argument ( LPDWORD lpcbData
).
Since you are passing in the buffer rgValue
, the size1
needs to be initialized to the sizeof(rgValue)
before calling RegQueryValueEx()
.
First, open
http://www.daniweb.com/forums/forum16.html
and there, click the area where it reads; "Databases Category (Click to show forums)"
I bet you'll manage to take it from there ...
I think you have an issue with precompiled headers.
In the noduri.cpp file, switch the order of your #includes to be
#include "stdafx.h" // <- first the precompiled header
#include "noduri.h" // then other includes follow
...
The above Wikipedia link briefly explains your issue, MSDN documents it more thoroughly - it can be rather complicated actually. You may want to turn the precompiled headers option off altogether.
Since this thread's title is "How to Get User Input from console -- safely.", I think it's appropriate to point out a little thing. Namely, in the Aia's version, decrementing size
before entering the for-loop is a recipe for buffer overflow if size
's initial value (for whatever reason) is zero.
So, to be on safer side ..
size_t obtainput (char *orig, size_t size)
{
size_t i = 0;
size_t total = 0;
/* Safety check ... */
if(size == 0)
return size;
--size;
...
Because I've not seen that difference documented in wikipedia here
Maybe I looked not in that direction or do we need to modify wiki, huh ? :)
That Wikipedia page links to Incompatibilities Between
ISO C and ISO C++ where this is explained, see the section "Empty parameter lists".
Based on your reply, I take that you are seeing too much red at the moment. But anyhow, I'd suggest that you get over that, and instead go through the replies you received, improving your tutorial. After all, that's the purpose of these replies, don't you think so too?
PS. Also note that your post could have been completely ignored, but it wasn't.
It looks like you are doing assignments (=) instead of comparisons (==), so check your if-statements ..
// You want to have ..
if(board[x][y] == '.')
...
And please use code tags.
Why the hell is there an i, does it means something, it's just an easy way to remember something or what?.
Relax and read some Wikipedia -> loop counter
FYI. If you don't like (too) short variable names, you are free to pick your poison. I think, C++ standard recommends that an identifier would be allowed to be 1024 characters long (the minimum).
Your for-loop is wrong ..
void getRaise(double pay[], int size)
{
// should rather be ..
for(int x=0; x <size; ++x)
...
The output does not really match with the code you've posted, too bad. But I suspect that something like following occurs ..
// You prompt for the dog's name ..
cout << "Enter dog1's name: ";
// Note: weight
cin >> dog1->weight;
// You actually typed in a string above
// and knocked out cin while doing that i.e. cin is
// non-functional at this point and the following
// attempt to read fails (weight retains its original value)
cin >> dog1->weight;
That kind of situation you can remedy using cin.clear()
perhaps along with cin.ignore()
.
what the heck is going on?
cout << "Your score is: " + finalPoints_
You want to change the '+' there to something else.
i think that this is ok with the scanf...it read the char exactly....i have donw this before...the problem is why the sin3 function doesn;t work....
Alright, now please understand that what you are doing regarding scanf()/a char
, is just downright wrong (you are corrupting the program's memory, believe it or not). If you don't fix those issues, simply expect most anything in terms of your program's behaviour/outcome.
By leaving the nullified pointers in the vectors, the second time around you iterate over the vectors, a crash is more than likely to happen (assuming these indices remain NULL pointers). Also you may want to check what the destructors are doing.
[EDIT]
Oh, and please read What are code tags
An additional thing that looks real bad and may be contributing to your problems ..
fflush(stdin);
you might read Why fflush(stdin) is wrong.
I'm having a hunch that this has got to do with const correctness.
Change
Vector3f(Vector3f &v);
to
Vector3f(const Vector3f &v);
As to the cout
problem, does your
overload look like this? (note: const
)
ostream & operator << (ostream &, const Vector3f &);
Are you sure about the return type of the assignment operator, that is returning reference vs. value?
If the problems persist (or even escalate), then maybe post more code (the .cpp files) + error messages.
PS. Rather include <cmath>
instead of <math.h>
. The same advice goes for all standard headers you include.
PSS. What is your compiler/version?
I ran it in debug mode, and it said there was a segfault. When it told me where the error was, it was in the ostream header file. Now what do i do?
At least one out-of-bounds (13 vs. 28) write ..
float percent[13];
...
for ( i = 0; i < 28; i++ )
{
percent[i] = ((float) total[year] )/ energy[year][i];
}
How about using const
throughout the program for specifying various sizes/dimensions?
const int rows = 123;
const int cols = 123;
int blah[rows][cols];
for(int rr = 0; rr < rows; ++rr)
{
for(int cc = 0; cc < cols; ++cc)
{
foobar(blah[rr][cc]);
}
}
Sorry but that doesn't ring a bell, the closest thing that comes into mind would be an explicit copy constructor, but that either wouldn't fully match what you are describing, as far as I understood. You might post more of the code (at least the header file).
PS. You might also have a second opinion and compile the code at Comeau
As to the original 'problem', would goto
be accepted?
Consider the following -- a lot less complicated and does the same thing
foo(float f[3]) { f1 = f[0]; f2 = f[1]; f3 = f[2]; }
Sorry AD, but you are missing the point here, which is to be sure that you can't pass an array of invalid size to the constructor.
Now, if you have a constructor foo(float f[3])
, you cannot hide foo(float *)
because they are threated as the same thing. So, foo(float f[3])
would not be allowed in this case.
Consider the following ..
struct foo
{
float f1, f2, f3;
// Accept a pointer to an array of 3 floats
foo(float (*f)[3])
{
f1 = (*f)[0];
f2 = (*f)[1];
f3 = (*f)[2];
}
private:
// Hide the unsafe constructor
foo(float *);
};
// And use it like ..
float bar[] = { 1.0f, 2.0f, 3.0f };
foo f( & bar);
// Will not compile ...
float x[4] = { 1.0f, 2.0f, 3.0f };
foo f( & x);
// Will not compile ...
float x[] = { 1.0f };
foo f( & x);
// Will not compile ...
float x[] = { 1.0f, 2.0f, 3.0f };
foo f(x); // Hidden ctor
Considering using fflush()
to have the output printed immediately
fprintf(stdout,"Hey guys..");
/* force the output onto the screen .. */
fflush(stdout);
struct timespec t_req, t_rem;
t_req.tv_sec = 1;
t_req.tv_nsec = 500;
if (nanosleep(&t_req, &t_rem) < 0)
return 0;
fprintf(stdout,"...What's up?");
OK, after all, it looks like you probably want to flush the (buffered) output, in order for it to show like you are expecting, even under the debugger. In other words, you may want to try e.g.
// Use 'endl' to have a newline inserted + output buffer flushed
cout << "Can you see me?" << endl;
// Use embedded '\n' and then 'flush'
cout << "Can you see me?\n" << flush;
It seems as if there is something I dont understand here with Sleep. If I use that function it will freeeze at the last cin.
So, you are saying that with Sleep()
enabled, the program freezes at line #132 (i.e. 'last cin'). So at that point you'll be unable to input anything and likewise you are not seeing any further output either?
How does the program terminate? Do you have to kill it via Task Manager or something alike?
The code you've posted will not even compile (snippet #1/line #11). So, maybe post the exact code that you are actually using.
should be initialized in constructor
I think you are still missing the point that jonsca has been making about static member variables, perhaps see C++FAQ
[10.10] Why can't I initialize my static member data in my constructor's initialization list?, and read the next one [10.11] too.
Adding to what's been said, just in case anyone is interested in trying out the code.
This
printf("Enter name (ENTER only will exit) : ");
scanf("%s",str);
will not work as intended, i.e. just pressing ENTER without any other input does not make scanf()
return. With the original gets()
it has worked. So, fgets()
would probably be a good choice there.
Then
ptr = (char *) malloc( strlen(str) ); // starting address of memory
strcpy(ptr,str);
simply corrupts the heap. It should rather be
ptr = malloc( 1 + strlen(str) );
strcpy(ptr,str);
so that there's room for the terminating '\0' character, added by the strcpy()
. And related to malloc()
, it's good to check that the allocation succeeded i.e. it did not return NULL.
Then, in q_enter()
maybe move the if (*str)
statement a bit higher so that the 'exit' case is handled properly (no need to go through malloc/strcpy in case the input length is zero).
PS. I think I somewhat agree with what jephthah is saying, but then again, if this original code really is taken from a book titled "C: The Complete Reference" I'm not so sure anymore after all.
correct me if i'm wrong
double celsius; printf("%lf temperature in celsius",celsius);
I think it was Dave Sinkula who once corrected me about this printf/double and %lf.
That line should rather read ..
printf("%f temperature in celsius", celsius);
In C99, the printf("%lf")
should have no effect, though (it's ignored).
Here's a version with some assert()
added. Run it in the debugger and you'll probably be spotting errors quite quickly.
#include <cassert>
void Array::merge (int first, int last)
{
const int arr_size = last-first+1;
int* merged = new int[arr_size];
int mid = (first + last) / 2;
int secList = mid + 1; // beginning of second list
int firstList = first; //beginning of first list
int j = first; // used for array index assignment
while ( (firstList <= mid) && (secList <= last) )// both lists #1 & #2 are not exhausted
{
if (data[firstList] < data[secList])// data in list #1 < data in list #2
{
// check j ...
assert(j < arr_size);
merged[j] = data[firstList];// <- data in list #1
firstList++;
}
else
{
// check j ...
assert(j < arr_size);
merged[j] = data[secList]; // <- data in list #2
secList++;
}
j++;
} // end while
if (firstList > mid)
{
for (int q = secList; q <= last; q++){
// check j ...
assert(j < arr_size);
merged[j] = data[q];
j++;
}
}
else
{
for (int r = firstList; r <= mid; r++)
{
// check j ...
assert(j < arr_size);
merged[j] = data[r];
j++;
}
}
for (int i = first; i <= last; i++)
{
data[i] = merged[i];// overwrite original positions with "merged"
}
delete [ ] merged; //commented out due to segmentation fault
merged = NULL;
}
I'd suggest you to check all your code for out-of-bound writes.
char text[10]
You need to increase the size of that array by one, if you intend to copy a literal such as "0x00000000" into it (you must account for the terminating '\0' character). Otherwise, you'll be writing out of bounds, which is not allowed.
PS. Maybe consider using std::string
s instead of char arrays.