How do I prevent command line closing after pressing Enter - c++

So I wanted to write a program which prints out a pyramid made out of "O", whose height is given by user input.
#include <stdio.h>
int main()
{
int n, i, j, k;
scanf_s("%d", &n);
{
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n - i; j++)
{
printf(" ");
}
for (k = 1; k <= 2 * i - 1; k = k + 1);
{
printf("O");
}
printf("\n");
}
return 0;
}
}
I'm a complete beginner, so if you have any advice, please do offer it. Anyways, I tried running it on a compiler on Android; seemed to work, printed out the pyramid.
Tried it on Microsoft Visual Studio. The command line opens, but after I put in the number and press "enter", the whole window just closes without giving me anything. How do I prevent this? Programs that don't need user input seem to run just fine.

For your described problem: Preventing console window from closing on Visual Studio C/C++ Console application
For your code, there seems to be a mistake, and currently your code will not produce a pyramid, but a slash of O. To solve this problem:
for (k = 1; k <= 2 * i - 1; k = k + 1); remove the ; from this line. Why this solved the problem?
When there is a ; after the loop, it means that the loop does nothing, and then the next three lines are:
{
printf("O");
}
Which means that there are only a single O prints out, instead of printing it in a loop.

Apart from the semicolon after the for (k = 1... loop, you have no bug in this code; if Visual Studio closes, the issue is with that program. (It could well just be closing because the program has finished execution, but I don't know that program).
Since you write that you are a complete beginner and you would appreciate advice, I'll offer some stylistic comments. But these are just comments on how I would do things differently if I were you, I am not saying that what you have is wrong.
Single-letter variable names: these will bite you. It is really easy to mix up i, j, and k since they are all kind of meaningless indexes. When your programs become more complex you will be happy to have meaningful variable names. Also, if you are trying to locate instances of a variable, searching for 'i' is a lot harder than searching for "spaces" or "spc"
Code block under scanf_s(): There is no reason to have this code inside a block--all that does is shift the internal code one tab right. Screenspace is precious.
You will likely find it more useful to iterate from 0 than from 1, as you will be using your iterator variable as an array index a whole lot. Getting into the habit of writing your loops as for (dex = 0 ; dex < max_val ; dex++) will serve you well. Note well that the comparison is "dex < max_val" and not "dex <= max_val"
The "k = k + 1" seems bad to me--people reading your code will need to stop and try to figure out why it's not just "k++" which what people are expecting and what you use in the other two loops. (And even for incrementing-by-more-than-one I'd expect something like "k += 2" not "k = k + 2")

Once console application returns from main method, the associated console window closes automatically. For Windows OS add a system("pause"); before your return 0; statement. For platform independent solution you can just show a prompt to user and wait for a key press before returning from main. Any character remaining in input buffer (enter from scanf in this case) must be cleared.
int main()
{
.........
.........
//clear input buffer
int d;
while ((d = getchar()) != '\n' && d != EOF) { }
printf("Press ENTER key to Continue\n");
getchar();
return 0;
}

You should include conio.h header file in your program and then simply place getch(); after your program's last cout statement.
I think that this would help the window from closing
it worked for me ;)

Put a cin command(C++) or a C equivalent at the very end just before return 0;, so it wont close. :>
Eg:
.
.
.
.
int control; cin>>control;
return 0;
}

Related

C++ time limit exceeded when it doesn't even execute the function

While I was solving a problem in LeetCode, I found something very strange.
I have this line which I assume gives me a time limit exceeded error:
s.erase(i-k, k);
when I comment(//) this line, it doesn't show me time exceed error, but the strange part was, it has never executed even when i didn't comment it.
below is the entire code.
and Here is the problem link.
class Solution {
public:
string removeDuplicates(string s, int k) {
char prev = s[0];
int cnt = 1;
cnt = 1;
for(int i = 1; i < s.size() + 1; i++){
if(s[i] == prev){
cnt++;
} else {
if(cnt == k){
// when input is "abcd" it never comes to this scope
// which is impossible to run erase function.
s.erase(i-k, k);
i = 0;
}
if(i >= s.size()) break;
cnt = 1;
prev = s[i];
}
}
return s;
}
};
When Input is "abcd", it never even go to the if scope where 'erase' function is in.
Although 'erase' function never run, it still affect on the time complexity, and I can't get the reason.
Does anyone can explain this? or is this just problem of LeetCode?
Many online contest servers report Time Exceeding when program encounters critical error (coding bug) and/or crashes.
For example error of reading out of bounds of array. Or dereferencing bad (junk) pointers.
Why Time Exceeded. Because with critical error program can hang up and/or crash. Meaning it also doesn't deliver result in time.
So I think you have to debug your program to find all coding errors, not spending your time optimizing algorithm.
Regarding this line s.erase(i-k, k); - it may crash/hang-up when i < k, then you have negative value, which is not allowed by .erase() method. When you get for example i - k equal to -1 then size_t type (type of first argument of erase) will overflow (wrap around) to value 18446744073709551615 which is defnitely out of bounds, and out of memory border, hence your program may crash and/or hang. Also erase crashes when there is too many chars deleted, i.e. for erase s.erase(a, b) you have to watch that a + b <= s.size(), it is not controlled by erase function.
See documentation of erase method, and don't put negative values as arguments to this method. Check that your algorithm never has negative value i.e. never i < k when calling s.erase(i-k, k);, also never i-k + k > s.size(). To make sure there is no program crash you may do following:
int start = std::min(std::max(0, i-k), int(s.size()));
int num = std::min(k, std::max(0, int(s.size()) - start));
s.erase(start, num);

C++ VS Debugger diverting behaviour?

I'm currently struggling to debug the following code part. I'm using VS2015 community edition on windows 10.
[(BR)] is a breakpoint
The following is a (slimmed down) version of my code. I basically have nested for loops that extract all points (X&Y coordinates) from all gameObjects.
As you can see I set two breakpoints.
I hit the debug button and it stops at the first breakpoint - success. Important local variable counterVertices is zero. Great as well.
Then I hit continue. It goes TO THE SAME BREAKPOINT THREE TIMES.
Then I get to the second breakpoint. counterVertices shows zero. Why?
int counterVertices = 0;
int counterIndices = 0;
int beginningOfPolygon = 0;
//GetData
for (auto& it : this->gameObjects) { //Iterate over all gameObjects
beginningOfPolygon = counterIndices;
for (int i = 0; i < it->getOutline().getNumber(); i++) { //Iterate over all points of the gameObject
[(BR)]this->vertices[counterVertices] = it->getRenderPoint(i).x;
counterVertices++;
this->vertices[counterVertices] = it->getRenderPoint(i).y;
counterVertices++;
[(BR)]if (this->vertices[counterVertices-2] == this->vertices[counterVertices-1] && this->vertices[counterVertices-1] == 0.0f) {
cout << "A point on 0/0." << endl;
}
this->vertices[counterVertices] = 0.0f;
counterVertices++;
//Add Line to draw
this->indices[counterIndices * 2] = counterIndices;
this->indices[(counterIndices * 2) + 1] = counterIndices + 1;
counterIndices++;
}
this->indices[(counterIndices * 2) - 1] = beginningOfPolygon;
}
I'm completely lost as this isn't even the problem I wanted to solve in the first place but rather got stuck on trying to figure on my original issue.
Thanks already for your time
PS: I have screenshots of the whole thing and the process is recreatable. I can clean and rebuild the solution, restart and do a backflip. Debugging behaviour doesn't change.
PPS: The program behaves/works in a way that suggest that counterVertices is increased correctly but the debugger information contradicts that.
Make sure you have optimizations turned off. Optimizations can really make it hard to debug, as values will be held in registers and not stored until it needs to. And code flow can be very unintuitive.

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

Strange characters appearing in 2D Char Array

I'm coding a game that utilizes a 'grid', which I have created using a 2 dimensional array of structs, which contain a char value and a boolean value. In my program's .h file, I declare the struct and create the grid.
struct Tile
{
char letter;
bool active;
};
Tile grid [6][5];
In my .cpp file, I initialize the grid so that all values are blank.
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
grid[i][j].active == false;
//grid[i][j].letter = '.';
//it always crashes when i try doing the above line
}
}
The function that prints the grid, printGrid, is below
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
cout << i;
//the above statement is for debugging purposes so that I can see
//which column easier
std::cout << grid[i][j].letter;
}
std::cout << std::endl;
}
cout << "1 2 3 4 5 6" << endl;
Now, the original goal was to have the default .letter value be '.'. But for some reason, when I tried to do this, there are disastrous results; the screen fills up with characters moving so fast I can't entirely see what they are (I recall some hearts and smiley faces), along with an obnoxious, rapid beeping. So I decided to leave that commented line out.
When I run the program without that line, for some reason, the "grid" always displays characters in certain spots, without any input from the user, or without me having expressly declared any values to that spot. For instance, the spot of the 1st column from the left and the bottom row, always has a character in it (grid[6][5].letter). It changes every time I run the program, and I've seen it range from a heart, to the letter A, to the spanish 'n' (the one with a ~ over it).
I thought to myself, "Hey, since grid[6][5] is the spots that are always buggy, I'll just declare those individual spot's .letter values to be blank (' ')!". That didn't work.
I've got no idea why this one spot is giving me trouble. There were other areas that would have an abnormal character, but I was able to neutralize them by setting their .letter values to blank. If anyone has any idea on how to fix this, pleas
EDIT: The other abnormal characters, which appear at grid[6][0], grid[6][1], grid[6][5], and grid[6][4], all make my program crash at later stages if I set them to blank (' '); however, blanking grid[6][5] is the one that makes it crash at the get go. I tried using a debugger, but it wasn't able to tell me anything helpful.
you're running over the end of your arrays
Tile grid [6][5]; needs to be Tile grid [7][6];
or you need to loop only to i < 6 and j < 5.

C++ Assignment don't work

Sorry for this very simple looking problem, but I have no idea what causes it:
In a C++ project I have a loop in a loop in a loop and have to leave the inner two so I have a variable for a query. In the first iteration it works fine, but in the second the assign from dtime to abbruch does not work. In the Debugger dtime has correctly the value "1" and abbruch "0" but this stays after the assignment. Both are of type long.
for (sect = 0; sect <= sections; sect++)
{
abbruch = 0;
for(line = 0; line < maxlines ; line ++)
{
abbruch = dtime[sect][0];
if(abbruch != 0)
{
break;
}
for (index = 0; index < 30; index ++)
{
if (complicated query)
{
dtime[sect][0] = DiffTime[maxlines * sect + line];
break;
}
}
}
}
I use VS2012 Ultimate.
Has anyone an idear how this can happen ot how to solve it?
Did you maybe mean to put this?
abbruch = dtime[sect][line];
(line instead of 0)
But also what Bathseba said is true. A break will only break one for-loop.
break will only take you out of the current for loop. In your case, the loop over index will not be called following a break when abbruch != 0 as that break will take you out of the loop over line. The other break statement will take you out of the loop over index.
That's the rationale, but, by far the best thing to do is to step through with a debugger. I wouldn't use break statements in this way as it's too confusing. Consider breaking the triple loop structure into function calls using return statements in place of breaks.
Also, it's a good idea to localise the interating variables in the for loops, e.g.
for (int sect = 0; sect <= sections; sect++)