I used to write C code with Visual Studio, and whenever I wrote "for" and then pressed TAB, it was automatically completed to an entire for loop, i.e.
for (size_t i = 0; i < length; i++)
{
}
Is there a way to enable that in VSCode as well? Even by using some extension?
Thanks!
Is there a way to enable that in VSCode as well?
Yes, you can add snippets and customize them according to your needs if the corresponding snippet is not already available, as shown below for the for loop shown in your question.
Step 1
Go to Files -> Preferences -> User Snippets
Step 2
After clicking on the User Snippets you will be prompted with a menu with different options as shown in the screen shot attached. Click on the option saying: New Global Snippets File
Step 3
When you click on New Global Snippets File, a file will open where you can add your required snippet. Since you've given the for loop that you want in C++, I will write the content that you want to place in that file:
{
"For Loop": {
"prefix": ["for", "for-const"],
"body": ["for (size_t i = ${1:0} ;i < ${2:length}; i++)", "{\t${0://add code here}", "}"],
"description": "A for loop."
}
}
Step 4
Save this file with the content shown above and then you will be able to use this snippet. For example, next time you write for you will be prompted with different options and you can press TAB for selecting that option and that snippet will be used at that point, as shown in the below screenshot :
I'm trying to pass some cmd commands using system() and I would like to be able to "communicate" with cmd, say I code in system("dir") in my mainwindow.cpp under my clicked function
this is what it looks like for example
void MainWindow::on_pushButton_login_clicked()
{
std::string platform_server_ip = ui->lineEdit_platform_server_ip->text().toStdString();
if (platform_server_ip == "dir"
{
QMessageBox::information(this,"Login", "all required log in details are correct");
close();
const char* c = platform_server_ip.c_str();
system(c);
system("ipconfig");
}
I would like to know why it behaves like this and if that's normal. I've included CONFIG += console
in my project file, and checked "run in terminal" (tried it also without) but it never shows me my desired outcome.
Instead what I get, is a blank terminal that pops up along side my GUI, and then when I enter "dir" in my GUI and hit enter, a cmd window pops up really fast and in less than a second, its gone. I've even tried it with system("ipconfig")andsystem ("pause")
as well as with one system command like this system("ipconfig" "&pause")
desired outcome: is just a normal execution of system("ipconfig"), followed by other system commands, that display the same result as typing them in cmd itself.
I've also tried all this in "qt Console application" and I either get the same result, or the output (what would normally be as output on cmd) is then found in "application output" of qt creator.
Is there another better way I can achieve what I want?
I'm truly a noob and would really appreciate some guidance.
You can try
system("cmd /k ipconfig");
This will open another terminal window which will stay open (k stands for keep) at the end of the command execution.
I think you don't need the CONFIG += console project setting, to achieve this. Calling system will start another process, which isn't related at all with the calling application.
If you want to start external programs from within a Qt application, you can use QProcess class, which lets you somehow interact with the started processes through standard in/out. For a very simple example, have a form with a push button and a text edit called textEdit; in the push button clicked slot:
QProcess process;
process.start("ipconfig");
process.waitForReadyRead();
ui->textEdit->setText(process.readAll());
process.waitForFinished();
This way, you won't see additional console windows, and the command output will be shown directly in your text edit.
This can be generalized in a function like this:
bool exec(QString command)
{
QProcess process;
process.start(command);
if(!process.waitForStarted())
{
return false; //the process failed to start
}
//etc...
return true;
}
Depending on whether this is not just a quick hack/tool, you can look at QProcess for more indepth control over your process so that you can read / write the child process pipes.
I've installed gtkmm3 via homebrew. My project links and builds without errors but never opens a window. xQuartz/X11 fires up upon successful build as well. It just seems to hang during the Gtk::Application::create() call. I've included my code below. Building on Xcode 5.1. Any help is much appreciated.
Thanks
#include <iostream>
#include <gtkmm-3.0/gtkmm.h>
int main(int argc, char * argv[])
{
std::cout << "Creating Application" << std::endl;
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "some.thing.here");
std::cout << "Creating Window" << std::endl;
Gtk::Window window;
std::cout << "Setting window title" << std::endl;
window.set_title("Window One");
std::cout << "Running App" << std::endl;
return app->run(window);
}
Gtk::Application::create() seems to hang because X11 isn't responding to it's request for a window. In it's current (default I assume) state only root can request a window.
Ideal solution (what worked best for me):
Go to Product > Scheme > Edit Scheme in the main menu of XCode. Make sure your current scheme (or whatever your dev scheme is) is selected in the fly out menu. On the modal that opens there are a few radio buttons. Select the 'run as root' option. Now X11 should respond to the request for the window.
Another solution:
Compile program and run with sudo.
An even more complex solution but if you intend to eventually let someone use this program via ssh...
Use xhost to add a user and enable ssh forwarding so you can run the compiled version via ssh without sudo. There are many docs explaining how to do this so I won't put the particulars here.
One other Note
XCode generates a main function with const char argv. Gtk::Application::create() won't take a const char argv. Remove const from main's argv and everything works.
I've spent most of my day trying to figure out why this error is occurring but it continues to mystify me.
I created a console application in Visual C++ and created one MFC application.Now, I want to add them into single project such way that when i compile the project ,it should open the console then will open Dialog box depending upon my commands......
I've added afx headers files,set configuration settings.
I want to know where to start whether starting point would in winmain() or int main()?
Is there any examples.?
Give me some links to know. the solution
Thank you in advance.
Create MFC dialog-based application. Project - Properties - Configuration Properies- Linker - Advanced - Entry Point, set wWinMainCRTStartup (assuming that project is Unicode). Linker - System - select Console. Build application. Now it opens Console window and the dialog from it.
Add some logic. For example, in my Application class cpp file I added the following:
#include "stdafx.h"
#include "testmfc.h"
#include "testmfcDlg.h"
#include <iostream> // add
#include <string> // add
using namespace std; // add
...
BOOL CtestmfcApp::InitInstance()
{
...
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
// ****** add this
string s;
cout << "Start application?" << endl;
cin >> s;
if ( s == "y" )
{
CtestmfcDlg dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
}
// ******
// Delete the shell manager created above.
if (pShellManager != NULL)
{
delete pShellManager;
}
return FALSE;
}
Now run application. If you answer "y" in the Console window, dialog is shown. Otherwise, application exits immediately. Implement your own logic based on this sample.
I have a collection of Boost unit tests I want to run as a console application.
When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run.
I see that if I run in release mode the console window stays up after the program exits, but in debug mode this is not the case.
I do not want to add 'system("pause");' or any other hacks like reading a character to my program. I just want to make Visual Studio pause after running the tests with debugging like it would if I were running in release mode. I would also like it if the output of tests were captured in one of Visual Studio's output windows, but that also seems to be harder than it should be.
How can I do this?
Try to run the application with the Ctrl + F5 combination.
http://connect.microsoft.com/VisualStudio/feedback/details/540969/missing-press-any-key-to-continue-when-lauching-with-ctrl-f5
In the older versions it would default to the console subsystem even if you selected "empty project", but not in 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this). Then select "project" from the menu bar drop down menus, then select "project_name properties" > "configuration properties" > "linker" > "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
Boost test offers the following usage recommendations for Visual Studio that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.
The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump through these errors using usual keyboard shortcuts/mouse clicks you use for compilation error analysis..."
Set a breakpoint on the last line of code.
I just copied from http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787/?prof=required:
The following works for me :-)
/////////////////////////////////////////////////////////////////////////////////////
Here is another reason the console may disappear. And the solution:
With the new Visual Studio 2010 you might see this behavior even when you use Ctrl + F5 aka "start without debugging". This is most likely because you created an "empty project" instead of a "Win32 console application". If you create the project as a "Win32 console application" you can disregard this as it does not apply.
In the older versions it would default to the console subsystem even if you selected "empty project", but not in Visual Studio 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this).
Then select "project" from the menu bar drop down menus, then select "project_name properties" → "configuration properties" → "linker" → "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
/////////////////////////////////////////////////////////////////////////////////////
If it is a console application, use Ctrl + F5.
In Boost.Test there is the --auto_start_dbg parameter for breaking into the debugger when a test fails (on an exception or on an assertion failure). For some reason it doesn't work for me.
See http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html
For this reason I have created my custom test_observer that will break into the debugger when there is an assertion failure or an exception. This is enabled on debug builds when we are running under a debugger.
In one of the source files of my unit test EXE file I have added this code:
#ifdef _DEBUG
#include <boost/test/framework.hpp>
#include <boost/test/test_observer.hpp>
struct BoostUnitTestCrtBreakpointInDebug: boost::unit_test::test_observer
{
BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::register_observer(*this);
}
virtual ~BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::deregister_observer(*this);
}
virtual void assertion_result( bool passed /* passed */ )
{
if (!passed)
BreakIfInDebugger();
}
virtual void exception_caught( boost::execution_exception const& )
{
BreakIfInDebugger();
}
void BreakIfInDebugger()
{
if (IsDebuggerPresent())
{
/**
* Hello, I know you are here staring at the debugger :)
*
* If you got here then there is an exception in your unit
* test code. Walk the call stack to find the actual cause.
*/
_CrtDbgBreak();
}
}
};
BOOST_GLOBAL_FIXTURE(BoostUnitTestCrtBreakpointInDebug);
#endif
You say you don't want to use the system("pause") hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit(). If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit() call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.
Or you could use boost_test "Test Log Output."
http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/user-guide/test-output/test-log.html
Then it won't matter whether the console window shows up at all AND your build logging can preserve the unit testing output as an artifact for examination on failed builds...
Adding the following line will do a simple MS-DOS pause displaying no message.
system("pause >nul | set /p \"=\"");
And there is no need to Ctrl+F5 (which will make your application run in Release Mode)
I would use a "wait"-command for a specific time (milliseconds) of your own choice. The application executes until the line you want to inspect and then continues after the time expired.
Include the <time.h> header:
clock_t wait;
wait = clock();
while (clock() <= (wait + 5000)) // Wait for 5 seconds and then continue
;
wait = 0;
You could also setup your executable as an external tool, and mark the tool for Use output window. That way the output of the tool will be visible within Visual Studio itself, not a separate window.
I start the app with F11 and get a breakpoint somewhere in unit_test_main.ipp (can be assembly code). I use shift-f11 (Step out) to run the unit test and get the next assembly instruction in the CRT (normally in mainCRTStartup()). I use F9 to set a breakpoint at that instruction.
On the next invocation, I can start the app with F5 and the app will break after running the tests, therefore giving me a chance to peek at the console window
Just use a logging library, like log4net, and have it log to a file appender.
Prompt for user input.
https://www.youtube.com/watch?v=NIGhjrWLWBo
shows how to do this for C++. For Node.js, this is taken right from the docs (and it works):
'use strict';
console.log('Hello world');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Press enter to continue...', (answer) => {
rl.close(); /* discard the answer */
});
Do a readline at the end (it's the "forma cochina", like we say in Colombia, but it works):
static void Main(string[] args)
{
.
.
.
String temp = Console.ReadLine();
}