#include <iostream>
int main(int argc, char* args[]) {
std::cout << 'hi';
std::cout << "hello";
}
When I run this code on windows, I don't see any output. What am I doing wrong?
EDIT
I think its an issue on my machine, hence my question. I understand it could work in theory, but I want to know why it isn't working in practice. (On my windows computer)
some of the compilers will close the output windows after executing the code, so we use getchar() or getch() or system("Pause") at the end of the code. so the output windows will wait for a key press event to close the output window. so you can see your output.
std::cout << "hi"; // Double quotes required.
output-here
You should see some output with your original program, though it may not be the desired output. 26729hello
The buffers of std::cout are not being flushed to the console.
Try Running:
#include <iostream>
int main(int argc, char* args[]) {
std::cout << "hi";
std::cout << "hello"<<std:endl;
}
The issue is that the std::cout is storing the text "hihello" in an internal buffer, but this buffer is not being "flushed" which in this case means written to the console window.
Related
I'm trying to send in an input value within the CLion + Gtest system (MacOS 10.14.4), but I get infinite "loading icon" and cannot type in anything into the "Run" window.
I created the tests using a tutorial. Normal tests work flawlessly, only std::cin refuses to work. std::cin works outside the test framework, when just opening a basic project and immediately using it. For this simple example, I only use one file "test.cpp", so nothing else is imported.
#include <gtest/gtest.h>
#include <iostream>
using testing::Eq;
using namespace std;
namespace {
class basicTest : public testing::Test {
public:
basicTest() {
}
};
TEST_F(basicTest, test1) {
cout << "\nWrite a number here: " << endl;
int i;
cin >> i;
cout << "You wrote " << i << endl;
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Running this produces the following:
The icon keeps spinning, but there is nowhere for me to write an input. In my original code, the first cout did not even output, so it's just a blank screen until I terminate it with the stop button.
Stopping early produces "Process finished with exit code 137 (interrupted by signal 9: SIGKILL)" but I don't think it's relevant.
I have not tried to use debug mode because it's not compatible with my MacOS version (that's another problem I'll fix eventually).
I am trying to implement GUI for a simple C++ using Qt to understand how it works. The C++ program and the GUI are in seperate projects in the same solution in VS 2015. The Qt program will call the C++ program using QProcess' start() function. The C++ console application will be running the background will the Qt program acts as an interface. My question is, how I do I pass values to the C++ program using QProcess and How do I obtain the output from the C++ program? Here is the sample program I am working with:-
The C++ Program
#include<iostream>
#include<fstream>
using namespace std;
void main() {
int a;
cout << "Enter a number" << endl;
cin >> a;
cout << "The Square of the number is " << (a*a) << endl;
ofstream write;
write.open("test.txt");
write << (a * a);
write.close();
}
The Qt Program
#include "FrontEnd.h"
#include <QtWidgets/QApplication>
#include <qprocess.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrontEnd w;
w.show();
QProcess p1;
p1.start("Interface.exe");
p1.write("5",5);
return a.exec();
}
I tried to pass the value using the write() function but it did not seem to work as the test.txt file remained empty. The Qt program I have written lacks the GUI features as I will be adding them once I figure out how to send and recieve data using QProcess. Thank you for your assistance!
You have many problems in the code you are showing:
You are passing write two arguments "5" and 5, this means that it will use 5 chars from the the char* "5". Absolutely, this is not what you want as this will lead to undefined behavior resulted from accessing memory that does not belong to your data.
Instead you should be using the second version of write which accepts a zero-terminated string, like this: p1.write("5");
In order to make cin in your console program know that the number it should read is finished, you should pass a new line after your number, so your call will end up like this: p1.write("5\n");
You should use the readyRead signal in the Qt program to get notified when your process has new output that you can read, and then you may call readAll from a slot which is connected to that signal.
For completeness, Here is how your code should be:
interface.cpp
#include<iostream>
using namespace std;
void main() {
int a;
cin >> a;
//No need to use file output
//it is simpler and more appropriate to read the output from stdout
cout << "The Square of the number is " << (a*a) << endl;
}
The Qt program
#include <QApplication>
#include <QWidget>
#include <QProcess>
#include <QDebug>
#include "FrontEnd.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrontEnd w;
w.show();
QProcess p1;
p1.start("Interface.exe");
p1.write("5\n");
QObject::connect(&p1, &QProcess::readyRead, [&p1](){
//output to qDebug, you may want to update some GUI component instead
qDebug() << p1.readAll();
});
return a.exec();
}
I am starting with C++ (Visual Studio 2015 and Windows 8.1), with this simple code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
But, the output screen shows nothing!, what shall I do?
Thanks in advance.
In Visual Studio, start the program with Ctrl-F5 and it will run and pause automagically for you. No additional code needed.
Your code is perfectly fine but the program currently only prints and exits right after, because this can happen very fast you might not be able to even see it,try pausing it :
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
cin.get();
return 0;
}
Also, make sure your Anti Virus isn't blocking Visual Studio.
Your code is just fine, however, if you execute it as a cmd program, the program window will close immediately, you might not be able to even see the output. You can write extra code to solve this problem by "pausing" the program:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout << "Hello world" << endl;
system("PAUSE");
return 0;
}
if you don't like include a windows.h file every time you type, you can add a "cin.get();" in the end of the code. But to be honest, since you are just a beginner, the coolest way I think you should try, is not to use Visual Studio to learn C/C++ but to install CodeBlocks(a simple but effective IDE) to write some codes that are not so long. You know, VS is for huge and complex projects and some practical program developing.
Another solution, platform dependent. My answer is for those of you who just need test pause for debugging purposes. It's not recommended release solution!
windows
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("pause");
return 0;
}
linux (and many alternatives)
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("read -rsp $'Press enter to continue...\n'");
return 0;
}
Detecting paltform
I used to do this on programming homework assignments, ensuring this only happens on windows:
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
#ifdef _WIN32
system("pause");
return 0;
}
Here's a good cheatsheet for ifdef macros and operating systems: http://sourceforge.net/p/predef/wiki/OperatingSystems/
The program exits on return 0; and window closes. Before this, you must pause the program. E.g you can wait for an input.
Here is a snippet from my code to do this. It works in both windows and linux.
#include <iostream>
using std::cout;
using std::cin;
// Clear and pause methods
#ifdef _WIN32
// For windows
void waitForAnyKey() {
system("pause");
}
#elif __linux__
// For linux
void waitForAnyKey() {
cout << "Press any key to continue...";
system("read -s -N 1"); // Continues when pressed a key like windows
}
#endif
int main() {
cout << "Hello World!\n";
waitForAnyKey();
return 0;
}
I am new to C++. I downloaded and run Dev-C++ and I write and run F9 this:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!";
return 0;
}
But no "Hello, world!" is printed, why?
Many IDE users have this problem. The program runs but it closes before you can see its results on the screen. One portable fix is to add this at the bottom of main before you return:
std::cin.get();
That way it will wait for you to enter some text before it exits.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!";
getchar();
return 0;
}
Add getchar() at the end of your program as a simple "pause-method" as consoles seems to close so fast, so you need to "delay" to see your console.
The output is printed to a terminal, and you don't have a newline etc.... very unlikely that you will see it, so
Add a newline to the output
make sure you have time to read the output before the terminal window closes (add a sleep or something)
Don't use using namespace as that is a bad practice and will lead to trouble in your programming.
So like;
#include <iostream>
#include <unistd.h>
int main()
{
std::cout << "Hello, world!" << std::endl;
sleep(2);
return 0;
}
What I want to do
redirect stdout and stderr to one or more files from inside c++
Why I need it
I am using an external, precompiled third-party library that produces a ridiculous amount of output, which I would like to redirect to a log file to keep the console clean.
Conditions
Compatibility is not a problem, the code will only run on Unix systems. The redirection should not only affect c++-style printing (std::cout << "hello world" << std::endl), but also c-style printing (printf("hello world\n")).
What I have tried so far
I have been browsing on stackoverflow for half a day, reading multiple answers to people having similar problems. With the help of these answers, I have been able to put together the following piece of code:
#include <stdio.h>
#include <iostream>
#include <fcntl.h>
#include "unistd.h"
const int stdoutfd(dup(fileno(stdout)));
int redirect_stdout(const char* fname){
fflush(stdout);
int newstdout = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
dup2(newstdout, fileno(stdout));
close(newstdout);
}
int restore_stdout(){
fflush(stdout);
dup2(stdoutfd, fileno(stdout));
close(stdoutfd);
return stdoutfd;
}
int main(){
redirect_stdout("/dev/null");
std::cout << "invisible 1" << std::endl;
restore_stdout();
std::cout << "visible 1" << std::endl;
redirect_stdout("/dev/null");
std::cout << "invisible 2" << std::endl;
restore_stdout();
std::cout << "visible 2" << std::endl;
return 0;
}
What I would expect to see:
visible 1
visible 2
What I actually see
visible 1
That is, when using this mechanism for the first time, it works - but if used again, restoring the output will not work.
Can somebody point out to me what I need to change in order to have the mechanism work infinitely often?
EDIT: Why it is different from what everyone else is doing?
Many people have similar questions (hence the "again", e.g. here). However, here, I specifically target a solution that works for C-style and C++-style printing, and have a particular focus on the reusability of the functions - something that is generally not addressed in other questions and answers.
In addition to afr0ck answer of freopen() I want to say that while using freopen() we should be careful. Once a stream like stdout or stdin is reopened with assigning the new destination(here the 'output.txt' file) always it remains for a program unless it has been explicitly change.
freopen("output.txt", "a", stdout);
Here the standard output stream stdout is reopened and assigned with the 'output.txt' file. After that whenever we use printf() or any other stdout stream like - putchar() then every output will goes to the 'output.txt'. To get back the default behavior (that is printing the output in console/terminal) of printf() or putchar() we can use the following line of code -
for gcc, linux distribution like ubuntu - freopen("/dev/tty", "w", stdout);
for Mingw C/C++, windows - freopen("CON", "w", stdout);
See the code example below -
#include <stdio.h>
int main() {
printf("No#1. This line goes to terminal/console\n");
freopen("output.txt", "a", stdout);
printf("No#2. This line goes to the \"output.txt\" file\n");
printf("No#3. This line aslo goes to the \"output.txt\" file\n");
freopen("/dev/tty", "w", stdout); /*for gcc, diffrent linux distro eg. - ubuntu*/
//freopen("CON", "w", stdout); /*Mingw C++; Windows*/
printf("No#4. This line again goes to terminal/console\n");
}
This code generate a 'output.txt' file in your current directory and the No#2 and No#3 will be printed in the 'output.txt' file.
Thanks
If you want to be able to reuse it, don't close stdoutfd in restore_stdout.
Are you looking for something like this :-
int main()
{
// Save original std::cin, std::cout
std::streambuf *coutbuf = std::cout.rdbuf();
std::streambuf *cinbuf = std::cin.rdbuf();
std::ofstream out("outfile.txt");
std::ifstream in("infile.txt");
//Read from infile.txt using std::cin
std::cin.rdbuf(in.rdbuf());
//Write to outfile.txt through std::cout
std::cout.rdbuf(out.rdbuf());
std::string test;
std::cin >> test; //from infile.txt
std::cout << test << " "; //to outfile.txt
//Restore back.
std::cin.rdbuf(cinbuf);
std::cout.rdbuf(coutbuf);
}
From my earlier answer
well i u'd better use freopen()
Usage Syntax:
freopen("RedToFile","r",stdout);
or
freopen("/dev/null","a",stdout);
the same goes for "stderr"
For C++ iostreams, you can use the non-const overload of rdbuf
to set std::cout to a std::filebuf. (This is best done by
means of an RAII class, since you have to restore it before
leaving main.) For C FILE*, you can use freopen, but
I don't think you'll be able to restore it.
FWIW: both of these solutions use only standard C++ or C, so
should be portable.
I was inspired by #POW and #James Kanze 's answers and put together a little RAII class for redirecting std::cout to a file. It is intended to demonstrate the principle.
Code:
#include <iostream>
#include <fstream>
#include <string>
// RAII for redirection
class Redirect {
public:
explicit Redirect(const std::string& filenm):
_coutbuf{ std::cout.rdbuf() }, // save original rdbuf
_outf{ filenm }
{
// replace cout's rdbuf with the file's rdbuf
std::cout.rdbuf(_outf.rdbuf());
}
~Redirect() {
// restore cout's rdbuf to the original
std::cout << std::flush;
_outf.close(); ///< not really necessary
std::cout.rdbuf(_coutbuf);
}
private:
std::streambuf* _coutbuf;
std::ofstream _outf;
};
// == MAIN ==
int main(int argc, char* argv[]) {
std::cout << "This message is printed to the screen" << std::endl;
{
// scope for the redirection
Redirect redirect{ "output.txt" };
std::cout << "This message goes to the file" << std::endl;
}
std::cout << "Printing to the screen again" << std::endl;
}
Output:
This message is printed to the screen
Printing to the screen again
Contents of the file "output.txt":
This message goes to the file