Looks like you are doing something like
ifstream ifs("foobar");
char chr[1];
// Read a char
ifs.get(chr);
Just change to plain char, i.e.
ifstream ifs("foobar");
char chr;
// Read a char
ifs.get(chr);
Looks like you are doing something like
ifstream ifs("foobar");
char chr[1];
// Read a char
ifs.get(chr);
Just change to plain char, i.e.
ifstream ifs("foobar");
char chr;
// Read a char
ifs.get(chr);
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
here is in english i just need to change the sin3 function cause in there something is wrong and the memory of system suffers
Could it be ..
scanf("%s %d", &myColchar,&myrow);
What do you think?
;)
It does work but when the word is being read from a file and then passed into that method it does not properly remove the punctuation.
Looking at the code you've posted (post #6), I notice that you've removed the following line ..
x.erase(std::remove_if(x.begin(), x.end(), &ispunct), x.end());
so, would that explain this behaviour or did you post wrong code?
in my mind my code is right but windows say no.....
You want to check your scanf() usage. Most of them seem to be right but some are dangerously wrong.
For example;
// A single char
char apantisi;
...
// '%s' expects an array of char (i.e. a string), not a single char
scanf("%s",&apantisi);
Instead that should be
// A single char
char apantisi;
// Use '%c' for a single char
scanf("%c", &apantisi);
Fixing all these scanf()
errors (i.e. scanf()ing a single char) should get rid of your program's crashes.
Looks like you are still having out-of-bounds issue(s), at least. Note that even reading something out-of-bounds may result in a crash/surprise-behaviour (and certainly is a programming error at any rate).
I'd suggest that you add the following assert()
to see it for yourself.
#include <cassert> // using assert()
void option2 (...)
{
...
cin >> choice;
sort ( energy, ref, sorted, 29, i );
assert(i + 1 < 14);
cout << energy[0][i+1] << endl << energy[1][i+1];
}
There may be other similar cases as well, so you need to carefully go through all of the code and make sure it doesn't do anything illegal. Using const
, as suggested earlier, would ease your job of keeping track of array bounds.
Instead of the 'XOR-trickery' there, consider using std::swap()
, like so ..
std::swap(input[i][mat], input[i+1][mat]);
std::swap(reference[i], reference[i+1]);
Or if std::swap()
is not allowed, then rather use a temporary variable for swapping.
Then in general, unless planned for later use, remove all unused parameters from function signatures, as in option2()
, total
, fossilfuel
and renewable
are not used for anything.
And lastly, you should use better, more descriptive variable naming ( bool t
=??), especially avoid using letter ell as an identifier (it looks a whole lot like 1).
An additional thing that looks real bad and may be contributing to your problems ..
fflush(stdin);
you might read Why fflush(stdin) is wrong.
The print()
method in the Book.h
is lacking a '}'.
Line #115, should it rather read
case 3: ofBB.push_back(rowb[jb]);break;
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
1>\main.cpp(71): error C2676: binary '[' : 'Account' does not define this operator or a conversion to a type acceptable to the predefined operator
In main()
, you have declared
Account acc;
That gives you a single instance of class Account
but you are trying to use it as if it were an array of pointers to Account
objects, hence the error. Perhaps try to employ an array of Account
, or if you are familiar with std::vector
, then a std::vector<Account>
might also do.
Then sorry to say, but as to the rest of the main()
, currently your code is so poorly formatted that the program flow is simply undetectable. If you are using Visual Studio 2005 or later, try auto-formatting the code by pressing;
Ctrl+A Ctrl+K Ctrl+F
to realize the difference. Furthermore, you could;
- make sure that the editor uses spaces instead of tabs
- configure the 'indent size' to a small number (e.g. 2)
see Tools / Options / Text Editor / C/C++ for these options.
>> for some reason when i run it the command prompt appears blank.
You have forgotten to use account_details()
.
MRKtack.exe!VisualEditBox::LineMinMax+0x6a
MRKtack.exe!VisualEditBox::Refresh+0x7e
MRKtack.exe!VisualEditBox::InternalPaint+0x3b
MRKtack.exe!SelectEditBox::MouseSetCaret+0x242
MRKtack.exe!UndoEditBox::MouseSetCaret+0x14a
MRKtack.exe!SelectEditBox::StartSelection+0x40
MRKtack.exe!EditBox::wmLbuttondown+0x130
MRKtack.exe!WndProc+0x2bd
USER32.dll!UserCallWinProc+0x18
USER32.dll!DispatchMessageWorker+0x2e4
USER32.dll!DispatchMessageW+0xb
MRKtack.exe!Window::MessageLoop+0x5f
MRKtack.exe!Window::Run+0x2b
MRKtack.exe!WinMain+0x82d
MRKtack.exe!__tmainCRTStartup+0x286
MRKtack.exe!WinMainCRTStartup+0xd
KERNEL32.dll!BaseProcessStart+0x3d
To point out at least one immediate problem, it gets 'stuck' in the LineMinMax()
doing some lengthy calculations there. When it stops responding, break it into the debugger and watch the values being used inside the loops.
There were a rather large number of warnings of many kinds, maybe you should be paying some attention to them.
Lines 31 and 33 are assignments instead of comparisons.
PS. In the future, try to be much more detailed than just stating "code is not working".
Now that's just wishful thinking ;)
Daniweb has a quite nice sortiment of smilies, but this makes me think that there's one missing, that would be: 'Icon Sigh', or some such.
i am using Dev c++ on win7 (64bit ) and there are no errors.
If you are compiling with GCC, then try compiling the code with the following two compiler switches:
-Wall
-pedantic
You'll probably be alerted to at least two problems.
Well, the first cout
takes place before you have read anything -> garbage.
Perhaps delete the count
variable, it's not serving any practical purpose at the moment (it only gets incremented once after the do/while loop is done) - unnecessary variables just add to the clutter, so to speak.
Also really consider using std::string
instead of those unsafe char arrays - as of now, you have no control over how much data gets read into the arrays.
[EDIT]
You could also format the code and keep it that way - for readability's sake.
Somewhat off-topic, only related to this zero-length thing, here is Herb Sutter's take on it When is a zero-length array okay?
As to the original 'problem', would goto
be accepted?
If i delete the ;, it reads the first number and the rest is gibberish.
OK, but you certainly will not want the semicolons there.
By looking at your first post, it seems that there are more integers per line than what you are reading now.
Try the following loop instead.
students.open("C:\\grades.txt");
count = 0;
int dummy; // Used for ignoring 3 numbers
// As long as count remains legal
// and all fields can be read ..
while
(
count < ARRAY_SIZE
&&
students >> first >> last
>> t1 >> t2
>> numbers[count]
>> attendance
>> dummy >> dummy >> dummy
)
{
++count;
}
After that loop exits, you might check the number of lines read and also use .eof()
to see whether there would be more input. Also a much safer practice would be to change to std::string
wrt. first
and last
.
Then when you print out the stored numbers, don't use ARRAY_SIZE
in the for()
loop, but rather limit the output to the number of items actually read or else you are likely to see garbage values.
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.
Both of your for()
loops end with a semicolon, that's a huge problem. Delete those semicolons and see how it changes the outcome.
What do you mean, my CarList stuff is after my car class set up..is this incorrect??
At the moment, your CarList
only has a constructor defined, all member methods (e.g. void insert(Car)
) lack the implementation (or you haven't posted all of the code).
Then a thing that is quite wrong in multiple places, for example
&Car::getMake;
You probably want to change that code to
carObject::getMake();
and fix the other similar errors too.
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?");
Try the following, in the dialog box's OnInitDialog()
handler ..
CDialog::OnInitDialog();
SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
Additionally if there was a way it could always be on top of other programs but still be minimized, that would be even better.
Sorry, but I don't quite understand what that would mean.
You might use a stringstream for that purpose. This has been answered probably a gazillion times, here we go again ..
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string filename ("data");
std::string extension (".txt");
std::stringstream sstrm;
for(int X=1;X<11;X++)
{
sstrm << filename << X << extension;
std::cout << sstrm.str().c_str() << std::endl;
// Get rid of the current content ..
sstrm.str("");
}
return 0;
}
Perhaps you should consult your professor?
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?
i come up with a additional set of numbers, but i don't know why.
Line #44 needs rewriting
while(inFile)
Change it to ..
while(inFile >> studentName >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
// rest of the code ...
}
Your while(inFile)
is a variant to the theme of using .eof()
in a loop control. Read Avoid Loop Control Using eof() courtesy of Dave Sinkula.
The code you've posted will not even compile (snippet #1/line #11). So, maybe post the exact code that you are actually using.
That was why I suggested a Truth Table... :icon_wink:
I know you did, but it just so much seems that the point still needs to be made, so to speak...
Basically, a thing that you need to understand is the fact that
while( ans != 'n' || ans != 'y' )
is effectively the same as writing
while( true )
And there is no way around that. :)
my question is still there that how can i place check on the input
that user can enter only 'y' or 'n'
Consider using logical AND (&&) ..
do
{
prompt the user ..
get the input ..
}
while(ans != 'y' && ans != 'n');
or logical OR (||) ..
do
{
prompt the user ..
get the input ..
}
while((ans == 'y' || ans == 'n') == false);
Try to think through your original if-statement to understand why it will not work.
You need to use the KEY_ENUMERATE_SUB_KEYS
flag when opening the key ..
// ..
if(RegOpenKeyEx(
HKEY_CURRENT_USER , "Software" , 0 ,
KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
&hkey) == ERROR_SUCCESS) {
// ..
Note that a successful RegEnumKeyEx()
call will change the value of the size
parameter to be the length of the subkey. So, you need to ensure that you pass in the real size of the name
buffer upon each call to RegEnumKeyEx()
.
See the documentation on InternetGetConnectedState()
The first parameter is a pointer to a DWORD (i.e. LPDWORD), which receives one or more of the flags, as described.
So, rather use ..
DWORD dwFlags;
BOOL bState = InternetGetConnectedState(&dwFlags, 0);
// .. check the state + the flags
It seems to be a quite tricky function wrt. correct interpretation of the received state/flags, so good luck.
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.
Actually, to be more specific, it appears to happen immediately before the free(cur) would be executed...which seems even odder to me.
Likely you are writing to already freed memory, outside this delete_from_list()
function. The debug memory management facilities kick in upon the attempt to free()
, catching the aforementioned error (-> runtime error message).
A minimal example that you could try out to see how it happens, would be along the lines of..
int main()
{
/* Allocate a node and initialize its examNumber to 1 */
struct node * p1 = alloc_node(1);
/* Allocate a node and initialize its examNumber to 2 */
struct node * p2 = alloc_node(2);
/* Make a list .. */
struct node * list = p1;
p1->next = p2;
p2->next = NULL;
/* free p1 .. */
list = delete_from_list(list, 1);
/* p1 still is accessible here, pointing to the freed memory,
* now write to that memory ..
*/
p1->next = NULL;
/* Try to free p2 .. */
list = delete_from_list(list, 2);
return 0;
}
For little more information on how this error gets caught, you might read Magic debug values.
[EDIT]
Also check that you are not trying to free anything twice/nor writing out-of-bounds.
Consider switching to unsigned char
s altogether, or at the minimum, cast to unsigned char
whatever you pass to isdigit()
.
PS. When you post code/error messages, please tick the "Disable smilies in text" option before you post (see your second post ^^).
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).
I've check it, the and nothing is really wrong with it; except from the fact it's not working?
So you are saying that you used the debugger and stepped through the code, including the LoadBMP()
function and everything worked as expected?
Perhaps you could post the code that exhibits this behaviour.
If you already haven't, then try debugging the constructor, that is, place a breakpoint at the following line and take it from there ..
TextureName = strlwr(strdup(Filename));
The code above would be possible if i want to paint all the 200 edit control the same colour right..?
Yes.
>> What if I want to paint them different colour..?
Then you have to arrange so that the colour/control mappings are stored somewhere. Just an idea, a std::map
might be handy ..
// A map ..
std::map<int /* control ID */, COLORREF /* the colour */> id_to_color;
// Then in the handler ..
HBRUSH CZilchDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// Should we change the attribute(s)?
if( < the condition here > )
{
// Get the edit control's id ..
int control_id = pWnd->GetDlgCtrlID();
// Use the current mapped colour ..
pDC->SetTextColor(id_to_color[control_id]);
}
return hbr;
}
Perhaps start by trying out something that simple to get some insight.
>> Is it possible to do the following..?
Don't store anything that is passed into the handler, those are pointers to temporary objects i.e. for a given edit control, the passed-in CDC * will vary/change.
PS. Are you serious about having 200 edit controls? I think the maximum number of any controls on a dialog is 255, so watch out for that limit.