Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a very strange error. I am writing a program in Cuda that emulates the Conway Game of Life. I transfered the 2D array to device and there is a if-case that check for the state's thread.
if(iam==-1)
{ //i am on
iam=0;
}
else if(iam==1)
{ //i am dying
iam=-1;
}
else //i am off
{
if(counter_alive==2)//two neighboors alive
{
iam=1; //i will be on
}
// iam = -999;
}
When the last line is in comment nothing works and the var "iam" has the first value. But if i drop the //, it will work. Of course, if the flow's code execute the else, the var "iam" will take the value -999.
Any ideas? Have i missed something?
Thanks in advance!
You do not show the initial value of the variable iam or counter_alive. Let us assume that the compiler has set it to 0. Of course even if the compiler just sets the space to a random value, this analysis would be the same.
if(iam==-1)
{ //i am on
iam=0;
}
Since the initial value is 0, then this fails and drops through
else if(iam==1)
{ //i am dying
iam=-1;
}
Again, since the initial value is 0, then it fails and drops through.
else //i am off
{
if(counter_alive==2)//two neighboors alive
{
iam=1; //i will be on
}
// iam = -999;
}
It enters here with a value of 0. However, since counter_alive has never been set, it is also 0 and the if fails.
Thus, the iam variable is never changed from 0. Note that since neither of the critical values changes, iam will never be reset from 0. If you uncomment the last line, it will always be explicitly set to -999 and will never change either. That is because you never test for 0 or 999. If you had it as -1 it would change to 0 and then never change unless you change counter_alive somewhere else to be 2.
Note that Explanation of CUDA C and C++ explains how the looping is handled as parallel processing. In that case, the reaction of the various items in the array may not be what you would expect in plain C (single stream) processing.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Hello everyone as the title says as I run through my code everything works fine, it loops correctly but somehow ends up always picking up the default case before restarting the loop.
I'll post my code through pastebin since it's quite long:
https://pastebin.com/TxvH3MhJ
while(myScore != "new" || myScore != "NEW" || myScore != "New"){
switch(s2){
case 1 :
switch(s3){
// code
}
default :
cout<<("\nSomething went wrong, please restart the program.");
break; //this statement works correctly.
}
default : //this statement is always brought up each time i type "new", i also added a cout s2 to check if actually somehow the variable was changing mid code but it prints out correctly.
cout<<("\nSomething went wrong please restart the program.");
cout<<s2;
break;`
p.s. I'm a beginner please bear in mind that probably the code is very rudimental although it is doing the job. at the moment the code just works if you enter 1s because i'm just working out the logic.
break; breaks out of the innermost switch (or loop) only. So you need to place it after inner switches too (unless you would need fall-through), like:
switch(s1) {
case 1:
switch(s2) {
...
}
break; // <== HERE
case 2:
...
break;
default:
....
break; // optional
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have some knowledge about C++, but I stumbled upon an problem. I want the user to enter some text, but when it takes longer than X seconds, the program will go on. I guess, it is not possible, but maybe you know something about it.
It will be in the command line, without GUI.
I am not certain how the programm will look like, but it will be something like a CMD-RPG. I wanted to use Quick Time Events to make it a little bit more exciting.
I cant comment so I will just leave this here
Input with a timeout in C++
Since I cannot comment, I will simply leave this as an answer.
One possible way to solve this problem is to have 2 threads:
Input capture thread: since receiving input is a thread-blocking action, you should have a thread that simply polls for user input, placing that input into a thread-safe buffer
Quick-time function on main thread: a function that will be responsible for executing the quick-time event. Something like the following could be done (pseudo code):
clear input buffer //the buffer provided by the input capture thread
bool success = false;
while(current time < ending time)
{
if(input buffer isn't empty)
{
get contents of input buffer and send contents to cout
if (user has finished input correctly)
{
success = true;
break;
}
clear buffer
}
}
return success;
For this to work, you would need to turn off echo on the command prompt (see this page for more info)
Although Diogo's reference is excellent (and informative), I believe this answer is more applicable than since the OP has indicated that this program will be ran on Windows.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I've seen it once or twice in a few places, but I can't seem to find this pattern while searching. What I want is, while in a loop, pause for a couple of milliseconds for user input, then continue.
so it would look something like this:
int main()
{
while (1)
{
//do stuff
//get user input, continue if there is nothing
//do stuff based off of user input
}
}
I'm using xemacs and g++ on Fedora 18 and I'm looking for a single keyboard keypress.
You'll (almost certainly) want to use the curses library.
If you want to pause to wait for input, you call halfdelay to set the time to wait for input. If the user hasn't entered anything in that time, it'll return ERR (or some error code anyway--been a while so I can't remember for sure what). If memory serves, however, the shortest delay you can specify is 1/10th of a second; there's no way to tell it to just pause for (say) up to 2 ms. Edit: thinking about it, it seems like there is a timeout (or something like that) that lets you set a timeout in milliseconds.
More often, you just want to react to input if there is any, and just continue other processing if here is none. In this case, you'd call nodelay.
Either way, you also want to call cbreak to disable line buffering at the OS level, so any key the user presses will be available to the program immediately instead of waiting for them to press return before you receive the input.
I'd guess you probably also want to call noecho() so the user's input isn't echoed by getch. For the kind of program you seem to be talking about, echoing the input command is rarely desired.
Then inside your loop, you'll call getch() to get the key input data (if any). If you get input, you process it. If it returns the error code to indicate there's no input, you continue your other processing.
So the code would be structured something like:
cbreak();
noecho();
nodelay(mywindow, true);
while (1) {
int ch;
if (ERR != (ch = getch()))
process(ch);
update_screen();
do_other_processing();
}
In the case of wanting a keyboard input, and then firing a trigger only if it is there, your best bet is essentially to use an event handler style system, something akin to how games detect input. What happens is usually something like this:
Event e;
while(Poll for event e) // Basically check if something has been triggered.
{
if(event type == certain key pressed){
// Do related stuff
}
}
You will essentially put this inside your main program loop, and every time that key, or some other trigger you specify is fired, it will call a function or do something else you specified.
Yeah. So, I'm trying to make a code for a guessing game. In this game, there's a hard mode. In hard mode, you have 15 guesses, and have to guess between 1 and 500. But my problem is this:
I'm trying to have hard mode save & display your wins/losses, but when it outputs the contents of wins.txt it outputs something like this:
Wins: 0x7fffee26df78
Losses: 0x7fffee26e178
It's really confusing me. Here's the part of the code I have for that:
ifstream losses_var("losses.txt");
ifstream wins_var("wins.txt");
losses_var>> loss;
wins_var>> win;
wins_var.close();
losses_var.close();
Then it gets called with:
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n"
If you would like to see the full source code, it's here: http://pastebin.com/gPT37uBJ
My second problem:
Hard mode won't display when you win. That's pretty much the whole problem. In my code, the loop for asking users for input uses
while (guess != randNum)
So at the end bracket I have what I want the code to display when a user wins, but it just doesn't run. It just stops. I would like it if someone could help me with this. The line that has the bug is line 97 through 105. Again, source code is here: http://pastebin.com/gPT37uBJ
You've got your variable names confused
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n";
should be
cout<<"Wins: "<< win <<"\nLosses: "<< loss <<"\n";
It's important to pick good variable names. One reason is so that you don't confuse yourself about what your variables mean (if you confuse yourself think how it's going to be for someone else looking at your code).
Others have already answered the output problem (win vs. wins). The other problem is probably in your logic of while loop nesting. The outer loop (while (guess != randNum)) starts, but its body contains the entire inner loop (while (guesses_left != 0)). This means that the outer condition is not checked again until the inner loop terminates, which means you've run out of guesses. Also note that if you guess correctly, inner loop will never terminate. You probably want something like this:
while (guesses_left > 0) {
// input user's guess
if (guess < randNum) {
// process it
} else if (guess > randNum) {
// process it
} else {
// it's equal, user won
// do what's necessary for a win
return 0;
}
}
// ran out of guesses
// do what's necessary for a loss
return 0;
You are not writing your variables win and loss to cout. From your pasted code, I can see that wins and losses are ofstream objects, which means you are probably seeing addresses there. I would advise you to choose more informative variable names to avoid hard to spot mistakes like this.
I have a function that creates and insert some numbers in a vector.
if(Enemy2.dEnemy==true)
{
pt.y=4;
pt.x=90;
pt2.y=4;
pt2.x=125;
for(int i=0; i<6; i++)
{
Enemy2.vS1Enemy.push_back(pt);
Enemy2.vS2Enemy.push_back(pt2);
y-=70;
pt.y=y;
pt2.y=y;
}
Enemy2.dEnemy=false;
Enemy3.cEnemy=0;
}
It should insert 6 numbers in two vectors, the only problem is that it doesn't - it actually inserts more.
I don't think the snippet will run unless Enemy2.dEnemy == true, and it won't stay true for ever.
The first time the snippet runs, then Enemy2.dEnemy is set to false and it shouldn't run again.
I don't set Enemy2.dEnemy to true anywhere except when the window is created.
If I insert a break point any where in the snippet, the program will work fine - it will insert ONLY 6 numbers in the two vectors.
Any ideas what's wrong here?
ok so i did some debugging.
i found that Enemy2.dEnemy=false; is being skipped for some reason.
i tried to do this to see if it was.
if(Enemy2.dEnemy)
{
pt.y=4;
pt.x=90;
pt2.y=4;
pt2.x=125;
for(int i=0; i<6; i++)
{
Enemy2.vS1Enemy.push_back(pt);
Enemy2.vS2Enemy.push_back(pt2);
y-=70;
pt.y=y;
pt2.y=y;
}
TCHAR s[244];
Enemy2.dEnemy=false;
if(Enemy2.dEnemy)
{
MessageBox(hWnd, _T("0"), _T(""), MB_OK);
}
else
{
MessageBox(hWnd, _T("1"), _T(""), MB_OK);
}
Enemy3.cEnemy=0;
}
well the message box popped saying 1 and my code worked fine. it seems that Enemy2.dEnemy=false; doesn't have time to run ;/
blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah!
ok i found where is the real problem which was causing to insert more than 6 numbers..
it was where i was asigning Enemy2.dEnemy=true;
if(Enemy2.e1)
{
Enemy2.now=time(NULL);
Enemy2.tEnemy=Enemy2.now+4;
Enemy2.e1=false;
}
if(Enemy2.tEnemy==time(NULL))
{
check=1;
Enemy2.aEnemy=0;
Enemy2.dEnemy=true;
}
the problem seems that the second if runs more than one time, which is weird!
First things first: get rid of that abominable if (Enemy2.dEnemy == true) - it should be:
if (Enemy2.dEnemy)
(I also prefer to name my booleans as a readable sentence segments like Enemy2.isABerserker or Enemy3.hasHadLeftLegCutOffThreeInchesBelowTheKnee but that's just personal preference).
Other than that, the only thing I can suggest is a threading problem. There's nothing wrong with that code per se, but there is a window in which two threads could enter the if statement and both start pushing values into your vector.
In other words, if thread 1 is doing the pushing when thread 2 encounters the if statement, thread 2 will also start pushing values, since thread 1 has yet to set dEnemy to true. And don't think you can just move the assignment to the top of the if block - that will reduce but not remove the window.
My advice is to print out the contents of the vectors in the situation where they have more than six entries and that may give a clue as to what's happened (post the output here if you wish).
Re your update that the second if below is running twice:
if(Enemy2.e1)
{
Enemy2.now=time(NULL);
Enemy2.tEnemy=Enemy2.now+4;
Enemy2.e1=false;
}
if(Enemy2.tEnemy==time(NULL))
{
check=1;
Enemy2.aEnemy=0;
Enemy2.dEnemy=true;
}
If this code is executed twice in the same second (and that's not beyond the bounds of possibility), the second if statement will run twice.
That's because time(NULL) give you the number of seconds since the epoch so, until that second is over, you may well be executing the contents of that if thousands of times (or more).
If this problem disappears when you put in a breakpoint or a diagnostic output message, that's a strong clue that the problem is undefined behavior, which is usually caused by something like dereferencing an uninitialized pointer or careless use of const_cast.
The cause of the problem probably has nothing to do with the code you're looking at. It's caused somewhere else and just happens to show up here. It's like someone being hit by a falling brick: the obvious symptom is a man lying unconscious on the sidewalk, but the real problem has nothing to do with the man or the sidewalk, it's several stories up.
If you want to find the cause of the error, remove your diagnostics until the problem reappears, then start removing everything else. Prune away all of the other code. Whenever the error stops, back up until it starts again; if you don't see the cause of the error, start pruning somewhere else. Eventually the bug will have nowhere to hide.