Paranthesis closure in Geany for c++ - indentation

After typing
int func(){
And pressing enter I'm getting like this , since I have enabled auto close plugin
int func(){
//cursor stays here }
But what i need is
int func(){
//cursor stays here
}
I'm able to achieve the required indentation by changing snippets.conf, but I have to press c and Tab, where
c=%brace_open%%cursor%%brace_close%
brace_open={\n\t
brace_close=\n}\n
Auto-close plugin settings:
is there any other way of achieving ?? Thanks in advance.

I haven't been able to figure out how to get exactly what you've indicated, but the Autoclose plugin can get close. Typing int func(){ and pressing Enter gives the following, where the | character represents the cursor location:
int func(){
|
}
EDIT:
My Autoclose settings are as shown below. But that turns out not to be the whole story. See after the image for more.
While looking into this some more, I discovered some strange behavior. I don't know if it's at the root of your problem or not, but it's maybe something to consider.
Autoclose worked as I described when pressing Enter on the main keyboard, but not when pressing Enter on the keypad, with or without NumLock enabled. In the latter case, I got the same result you did.
I normally use an antique IBM Model M keyboard, so to eliminate any chance of the problem being caused by the keyboard itself, I tried a modern USB keyboard with keypad. The results were exactly the same.
Having a suspicion as to what was happening, and since it's open source, I pulled down the Autoclose source code and took a look. And found...
static gboolean
auto_close_chars(
AutocloseUserData *data,
GdkEventKey *event)
{
...
else if (ch == GDK_Return)
{
return improve_indent(sci, editor, pos);
}
...
}
A general search for GDK_Return turned up gdkkeysyms.h that defines all of the GDK key codes. In that, there's GDK_Return and also GDK_KP_Enter, where "KP" means "keypad". Since Autoclose doesn't recognize GDK_KP_Enter, it'll fail to respond to pressing Enter on the keypad.
So, if you're using a full keyboard with keypad, it should work ok so long as Enter on the main keyboard is being used. On the other hand, If you're using a laptop where there's only one Enter key, all bets are off.

Check out https://plugins.geany.org/autoclose.html for autoclose plugin. This will solve your problem.
In Linux you can directly install it by
sudo apt-get install geany-plugin-autoclose

Related

Indentation after for instruction in xcode doesn't work

I've been using xcode for some months and this has never happened before, i'm not sure whether i pressed something i shouldn't have or meddled with the settings. Basically i write something like for(int i=1;i<=n;i++) and press enter, and the cursor is on the next line above the instruction, so there's no visual subordination of what I'm about to write next.
If i press the tab key before writing a new instruction below and then write for instance cout<<n-i<<endl;, the moment I press ; , the entire thing is moved in the same column(if that makes sense) again. This doesn't happen with other instructions like while or if. Help?
Normally indentation occurs when you open a block, as in type {. If you're using a blockless if then the code editor has to figure out after the fact what you're doing.
I'm not able to reproduce your problem, but here are a few tips :
To format a selection in the editor
Main menu : Editor > Structure > Re-indent ( or ^I )
To remove the automatic formatting when pressing ;
User Preferences : Text Editing > Automatic indent for : Uncheck the “;” box

Trying to display a text through CMD with C++ and I am presented with a error [duplicate]

This is a probably an embarasing question as no doubt the answer is blindingly obvious.
I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!
Now try it...it should work
Starting from Visual Studio 2017 (15.9.4) there is an option:
Tools->Options->Debugging->Automatically close the console
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.
Here is a way for C/C++:
#include <stdlib.h>
#ifdef _WIN32
#define WINPAUSE system("pause")
#endif
Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.
Goto Debug Menu->Press StartWithoutDebugging
If you're using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER>.
try to call getchar() right before main() returns.
(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).
"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.
I ended with
int main() {
...
#if _DEBUG
LOG_INFO("end, press key to close");
getchar();
#endif // _DEBUG
return 0;
}
Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.
just put as your last line of code:
system("pause");
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
Change "Command" to the full path to runthenpause.bat.
Hit OK.
Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.
add “| pause” in command arguments box under debugging section at project properties.
You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:
int a = 0;
scanf("%d",&a);
return YOUR_MAIN_CODE;
and this way the window would not close until you enter data for the a variable.
Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).
If this doesn't work then add the following to the end of your code:
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
This wait for you to press a key to close the terminal window once the code has reached the end.
If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.
A somewhat better solution:
atexit([] { system("PAUSE"); });
at the beginning of your program.
Pros:
can use std::exit()
can have multiple returns from main
you can run your program under the debugger
IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)
Cons:
have to modify code
won't pause on std::terminate()
will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:
extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
if (IsDebuggerPresent())
atexit([] {system("PAUSE"); });
...
}
Either use:
cin.get();
or
system("pause");
Make sure to make either of them at the end of main() function and before the return statement.
You can also use this option
#include <conio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
.
.
.
getch();
return 0;
}
In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.
Go to "View" then select "Property Manager"
Right click on the project/solution and select "Property". This opens a Test property page
Navigate to the linker then select "System"
Click on "SubSystem" and a drop down appears
Choose "Console (/SUBSYSTEM:CONSOLE)"
Apply and save
The next time you run your code with "CTRL +F5", you should see the output.
Sometimes a simple hack that doesnt alter your setup or code can be:
Set a breakpoint with F9, then execute Debug with F5.
Since running it from VS attaches the VS debugger, you can check for an attached debugger:
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached. Press any key to exit.");
Console.ReadKey();
}
I guess the only caveat is that it'll still pause if you attach any other debugger, but that may even be a wanted behavior.
Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://learn.microsoft.com/en-us/dotnet/api/system.console.readline for details.
Visual Studio 2015, with imports. Because I hate
when code examples don't give the needed imports.
#include <iostream>;
int main()
{
getchar();
return 0;
}
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
It should be added that things have changed since then. On Windows 11 (probably 10, I can't check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.
If it's set to close when a program exits with zero, then it will close, even if VS is told otherwise.
Go to Setting>Debug>Un-check close on end.

cmd shell flashes across in VS code [duplicate]

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?
If you are using Visual Studio and you are starting the console application out of the IDE:
pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.
Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.
That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.
At the end of your main function, you can call std::getchar();
This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).
You need to #include <cstdio> for getchar.
The solution by James works for all Platforms.
Alternatively on Windows you can also add the following just before you return from main function:
system("pause");
This will run the pause command which waits till you press a key and also displays a nice message Press any key to continue . . .
If you are using Microsoft's Visual C++ 2010 Express and run into the issue with CTRL+F5 not working for keeping the console open after the program has terminated, take a look at this MSDN thread.
Likely your IDE is set to close the console after a CTRL+F5 run; in fact, an "Empty Project" in Visual C++ 2010 closes the console by default. To change this, do as the Microsoft Moderator suggested:
Please right click your project name and go to Properties page, please expand Configuration Properties -> Linker -> System, please select Console (/SUBSYSTEM:CONSOLE) in SubSystem dropdown. Because, by default, the Empty project does not specify it.
I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.
Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.
[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.
Before the end of your code, insert this line:
system("pause");
This will keep the console until you hit a key.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause"); // <----------------------------------
return 0; // This return statement isn't necessary
}
Call cin.get(); 2 times:
//...
cin.get();
cin.get();
return 0
}
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
I just do this:
//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;
Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.
Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.
Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.
Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.
Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.
cin.get();
If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.
Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.
Add the following lines before any exit() function or before any returns in main():
std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");
For Visual Studio (and only Visual Studio) the following code snippet gives you a 'wait for keypress to continue' prompt that truly waits for the user to press a new key explicitly, by first flushing the input buffer:
#include <cstdio>
#include <tchar.h>
#include <conio.h>
_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();
Note that this uses the tchar.h macro's to be compatible with multiple 'character sets' (as VC++ calls them).
Use #include "stdafx.h" & system("pause"); just like the code down below.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
std::cout << "hello programmer!\n\nEnter 2 numbers: ";
int x, y;
std::cin >> x >> y;
int w = x*y;
std::cout <<"\nyour answer is: "<< w << endl;
system("pause");
}
simply
#include <cstdio>
int main(){
// code...
std::getchar();
std::getchar();
return 0;
}
for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately.
so what we aim to is a simple way of preventing a program from finishing after it outputs everything.
Of course there are more complex and clean ways to solve this, but this is the simplest.
Similar idea to yeh answer, just minimalist alternative.
Create a batch file with the following content:
helloworld.exe
pause
Then use the batch file.
See if your IDE has a checkbox in project setting to keep the window open after the program terminates. If not, use std::cin.get(); to read a character at the end of main function. However, be sure to use only line-based input (std::getline) or to deal with leftover unread characters otherwise (std::ignore until newline) because otherwise the .get() at the end will only read the garbage you left unread earlier.
This seems to work well:
cin.clear();
cin.ignore(2);
If you clear the buffer first it won't be a problem when you read the next one.
For some reason cin.ignore(1) does not work, it has to be 2.
You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:
#echo off
:1
cls
call helloworld.exe
pause >nul
goto :1
If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....
I'm putting a breakpoint at the last return 0 of the program. It works fine.
I used cin.get() and that is worked but one day I needed to use another cin.get([Array Variable]) before that to grab a ling string with blank character in middle of. so the cin.get() didn't avoid command prompt window from closing. Finally I found Another way:
Press CTRL+F5 to open in an external window and Visual Studio does not have control over it anymore. Just will ask you about closing after final commands run.
I tried putting a getchar() function at the end. But it didn't work. So what I did was add two getchar() functions one after another. I think the first getchar() absorbs the Enter key you press after the last data input. So try adding two getchar() functions instead of one
Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)
just use cin.ignore() right before return 0; twice
main()
{
//your codes
cin.ignore();
cin.ignore();
return 0;
}
thats all
you can try also doing this
sleep (50000);
cout << "any text" << endl;
This will hold your code for 50000m, then prints message and closes. But please keep in mind that it will not pause forever.
Here's a problem, not so obvious. Somehow I had added a debug breakpoint at the very last line of my program. } Not sure how I did that, perhaps with an erroneous mouse click while jumping between different screens. I'm working in VS Code.
And when I go to debug, the system jumps immediately to that breakpoint. No error message, no interim output, nothing. I'm like, how did the program rush thru all my set breakpoints? This took too long to figure out.
Apparently the system sees that last line breakpoint as a "first" stop. The simple fix? Delete that breakpoint, doh! (insert forehead slap here.)
All you have to do set a variable for x then just type this in before the return 0;
cout<<"\nPress any key and hit enter to end...";
cin>>x;

Kate (text editor) indentation, c++

I use the kate text editor for writing c++ code. I really like the editor except for its indentation behavior which drives me mad. I have the following problem: If I want to write code like
if( true )
{
//code
}
the indentation messes everything up initially: instead of inserting a tab and jumping to the position marked "//code" when hitting enter, kate just inserts a single blank space. So to describe it more in detail: You start from
if( true )
{//your cursor is here
}
and on pressing enter, kate produces something like
if( true )
{
[ ]//your cursor is here
}
where '[ ]' stands for a single blank space. But instead, I want kate to insert a tabulator to give the result indicated at the start. Or, to repeat it more verbosely, I want that kate gives me
if( true )
{
<tabulator>//your cursor is here
}
on hitting enter. I have played around with all settings and can not make it work. It drives me crazy. I selected "default identation mode normal", "Ident using tabulators" (8 characters). Does anybody know how to customize this behavior? I looked up the katerc file but couldn't find any options that would help me...
edit: I should add that it would be ok if kate would just give me
if( true )
{
//your cursor is here
}
on pressing enter. But this additional blank space is absolutely annoying.
Ok, I tried for half an hour, I don't know why I found out how to do it right AFTER posting the question :). So in case anybody has the same issue, here is the "solution": I missed that kate seems to have a global setting for the indentation mode as well as a local one for every file. In my case - for some reason - my file had special indentation options set. You can alter them via the menu bar by chosing "Tools -> Indentation". This local option overrides the global one! Or the global one is just the default for the local options, I don't know exactly...
You can create a config file .kateconfig and add the variables kate: replace-tabs off; tab-indents: true;
More on this in the manual.

cursor blinking removal in terminal, how to?

I use the following lines to output my simulation's progress info in my c++ program,
double N=0;
double percent=0;
double total = 1000000;
for (int i; i<total; ++i)
{
percent = 100*i/total;
printf("\r[%6.4f%%]",percent);
}
It works fine!
But the problem is I see the terminal cursor keeps blinking cyclically through the numbers, this is very annoying, anyone knows how to get rid of this?
I've seen some programs like wget or ubuntu apt, they use progress bar or percentages too, but they seems no blinking cursor issue, I am wondering how did they do that?
Thanks!
You can hide and show the cursor using the DECTCEM (DEC text cursor enable mode) mode in DECSM and DECRM:
fputs("\e[?25l", stdout); /* hide the cursor */
fputs("\e[?25h", stdout); /* show the cursor */
Just a guess: try to use a proper number of '\b' (backspace) characters instead of '\r'.
== EDIT ==
I'm not a Linux shell wizard, but this may work:
system("setterm -cursor off");
// ...display percentages...
system("setterm -cursor on");
Don't forget to #include <cstdlib> or <iostream>.
One way to avoid a blinking cursor is (as suggested) to hide the cursor temporarily.
However, that is only part of the solution. Your program should also take this into account:
after hiding the cursor and modifying the screen, before showing the cursor again move it back to the original location.
hiding/showing the cursor only keeps the cursor from noticeably blinking when your updates take only a small amount of time. If you happened to mix this with some time-consuming process, your cursor will blink.
The suggested solution using setterm is not portable; it is specific to the Linux console. And running an executable using system is not really necessary. But even running
system("tput civis");
...
system("tput cnorm");
is an improvement over using setterm.
Checking the source-code for wget doesn't find any cursor-hiding escape sequences. What you're seeing with its progress bar is that it leaves the cursor in roughly the same place whenever it does something time-consuming. The output to the terminal takes so little time that you do not notice the momentary rewrite of the line (by printing a carriage return, then writing most of the line over again). If it were slower, then hiding the cursor would help — up to a point.
By the way — this cursor-hiding technique is used in the terminal drivers for some editors (vim and vile).
Those apps are probably using ncurses. See mvaddstr
The reason the cursor jumps around is because stdout is buffered, so you don't know actually how many characters are being printed at some point in time. The reason wget does not have a jumping cursor is that they are actually printing to stderr instead, which is unbuffered. Try the following:
fprintf(stderr, "\r[%6.4f%%]", percent);
This also has the advantage of not cluttering the file if you are saving the rest of the output somewhere using a pipe like:
$ ./executable > log.data
Press insert key...if that doesn't work then press the fn key in your keyboard.
This will definitely work
Hope this helps