no output in console window:codeblocks - c++

Heya I have installed codeblocks..on windows7
codeblocks-13.12mingw-setup-TDM-GCC-481.exe
my program is building but after executing i am getting a console window only with a cursor and no output. I tried it with many other programs but the same thing is happening.
I have also set all the settings to default and have also re installed codeblocks.
I am attaching snippet of the console window for the program code:
#include <stdio.h>
int main()
{
printf("helloworld%s")
return 0;
}
Even the default program was not working because it failed to recognize iostream.
PLease help..!

You forgot the ; at the end of the printf() line, you should have a syntax error when compiling.
The %s doesn't mean any sense if there is no additionnal argument. It is used when you want to print a string stored in a variable. Example:
int main(int argc, char** argv) {
char str[] = "world!";
printf("Hello %s\n", str);
}
will print "Hello world!".
Unless you know what you're doing, you should add a \n at the end of the printed line (before output on stdout are buffered, and printed when the buffer is full : Is stdout line buffered, unbuffered or indeterminate by default?)

Related

Get the last string printed in C/C++

I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.
so I have the function itself:
void f_sequence(char sequenceStr[])
{
//logic...
if(condotion1)
printf("somthing1");
else if(condotion2)
printf("somthing2")
(...)
}
and then the tester:
TEST(TesterGroup, TesterName)
{
f_sequence("input");
EXPECT_EQ("somthing1", /*how do i get the output?*/);
}
Is it possible?
The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.
Redirect the standard output to a buffer.
Live on Coliru
#include <stdio.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int stdoutSave;
char outputBuffer[BUFFER_SIZE];
void replaceStdout()
{
fflush(stdout); //clean everything first
stdoutSave = dup(STDOUT_FILENO); //save the stdout state
freopen("NUL", "a", stdout); //redirect stdout to null pointer
setvbuf(stdout, outputBuffer, _IOFBF, 1024); //set buffer to stdout
}
void restoreStdout()
{
freopen("NUL", "a", stdout); //redirect stdout to null again
dup2(stdoutSave, STDOUT_FILENO); //restore the previous state of stdout
setvbuf(stdout, NULL, _IONBF, BUFFER_SIZE); //disable buffer to print to screen instantly
}
void printHelloWorld()
{
printf("hello\n");
printf("world");
}
int main()
{
replaceStdout();
printHelloWorld();
restoreStdout();
// Use outputBuffer to test EXPECT_EQ("somthing1", outputBuffer);
printf("Fetched output: (%s)", outputBuffer);
return 0;
}
References: http://kaskavalci.com/redirecting-stdout-to-array-and-restoring-it-back-in-c/
I don't know if it's possible to get what was last printed, but if you control the environment before your test function is called, you can redirect where standard output goes, which lets you write it to a file, which you can then check.
See this old answer which IMO was neglected. The example from it is modified here:
FILE *fp_old = stdout; // preserve the original stdout
stdout = fopen("/path/to/file/you/want.txt","w"); // redirect stdout to anywhere you can open
// CALL YOUR FUNCTION UNDER TEST HERE
fclose(stdout); // Close the file with the output contents
stdout=fp_old; // restore stdout to normal
// Re-open the file from above, and read it to make sure it contains what you expect.
Two ways:
If you're on a POSIX compatibile system, you can redirect the output of the program to a file using >, then read from the file later to confirm that the output is correct.
The other way is something like this:
freopen("output.txt", "w", stdout);
f_sequence();
freopen("/dev/tty", "w", stdout);
for POSIX compatible systems. On other platforms you'd need to change the "/dev/tty" to something else. I'm not aware of a completely portable way to do this.
And then read from output.txt. What the above snippet does is change what stdout is, so that it prints to a file instead of the normal stdout.
One solution: You can write a separate program that executes the function, and in the unit test, you can execute that program as a sub process and inspect the output. This can be done with std::system, but be very careful to not pass any non-constant input to it. You don't want shell injection vulnerability even in a unit test. System specific functions exist that avoid the use of shell in the subprocess.
Another solution, which is possible at least on POSIX: Replace the the standard out / err streams with file descriptors, and read the files afterwards.
Googletest specific: There seems to be testing::internal::CaptureStdout, which appears to implement the idea of replacing standard streams. But as the namespace implies, this is not official API, so may change in future.
There is a solution ( in C ) for an API call ( cmd_rsp ) with source code here, that when called in your program, creates a separate process, and pipes to both stdin and stdout, from which it accepts a command and returns the response via an auto sizing buffer. Similar in concept to popen(...).
A simple use case:
char *buf = NULL;
/// test cmd_rsp
buf = calloc(BUF_SIZE, 1);
if(!buf)return 0;
if (!cmd_rsp("dir /s", &buf, BUF_SIZE))//note the first argument can be any legal command that
//can be sent via the CMD prompt in windows,
//including a custom executable
{
printf("%s", buf);
}
else
{
printf("failed to send command.\n");
}
free(buf);

How can I enter continuously by another C++ program in C system / popen command?

I want to build a compile system in an online judge system.
Environment: Ubuntu 12.04 LTS, g++ version 4.9
My workflow is "Compile cpp" -> "Execute it" -> "Record message".
But I got some problems when "the cpp file exist 'scanf' or 'cin' commands".
Because this is a auto-compile & run program, there is an other input need to load. (Is a string from function call not enter in terminal by myself)
My problem
How can I run the executeCommand (below code in compiler.cpp), using the string input (below too) to enter for this program. If the executed program exist any scanf, cin or other commands.
compiler.cpp
This is system command version, can replace to popen command too.
#include <string>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char ** argv) {
// Compiler one cpp file.
string compileCommand = "(g++ --std=c++11 ./main.cpp -o ./main.out) 2> main.err";
system(compileCommand.c_str());
// Execute this program.
string executeCommand = "(time timeout -k1s 0.01s ./main.out) > result.txt 2> time.txt";
system(executeCommand.c_str());
// I want the above main.out will scanf from this string.
string input = "Hello world, this is first line.\nThis is second line.";
return 0;
}
main.cpp
#include <stdlib.h>
#include <stdio.h>
int main () {
char str[256];
scanf("%s", str);
printf("%s\n", str);
return 0;
}
You probably need popen(3) (and you flagged your question as such).
FILE*pcmd = popen("time ./main.out", "w");
if (!pcmd) { perror("popen"); exit(EXIT_FAILURE); };
fprintf(pcmd, "Hello world, this is first line.\n");
fprintf(pcmd, "This is the second line.\n");
fflush(pcmd);
int bad = pclose(pcmd);
if (bad) {fprintf(stderr, "pclose failed %d\n", bad); };
Be aware of code injection issues, in particular when passing a computed command to popen or system
You might need some event loop around poll(2). Then use fork, execve, pipe and other syscalls(2) explicitly, so read Advanced Linux Programming
All you need is a pipe, system( "echo YOUR_STRING | ./main.out " )

fprintf() / std::cout doesn't print part of the string to stdout/stderr

I have this strange problem with stdout/stderr.
I want to apologize for not being able to put here the original code, it's too long / too many libraries dependent etc...
So please let me know if you ever encountered anything like it, or what may cause this issue without getting the original code, only the idea and examples of the simple things I tried to do:
I'm using g++ (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4) on RHEL 6.3
I couldn't isolate the problem for putting it here, I'll give code examples of what I did.
fprintf() / printf() / std::cout stops working after a while.
I'm using boost::asio::io_service with deadline_timer in order to call a my_print() function.
This my_print() function prints to screen every 1 second some information.
In order to print, I use alignments, like the following:
fprintf(stdout, "%*s\n", -printWidth, someEnumToStr[i]);
fprintf(stdout, "%s\n", aString);
fprintf(stdout, "%u\n", num);
While aString is a std::string. Sometimes I construct aString from std::ostringstream.
Sometimes I construct it with snprintf().
I have an std::map with information, exactly 16 elements inside the map. I iterate over it, and for each element I try to print data with the example of fprintf() above.
For an unknown reason, the line of element 16 isn't printed.
If I call the executable, and redirect stdout to a file (./a.out > aaa.txt) the line of element 16 is getting printed.
If I open a new FILE* and fprintf() to this file, again, everything is getting printed (all lines, including line of element 16)
Before using fprintf() I tried to use std::cout (and alignments with std::cout.width(printWidth) << std::left...), The same behavior happened, but when line 16 wasn't drawn, stdout got stuck (I mean, the program still worked, but nothing was printed to stdout never again. I had to call std::cout.clear() for it to work again). Since a point in the code, which I couldn't lay my hands on, std::cout.failbit and badbit were 1.
If I run the code with valgrind this behavior doesn't happen. valgrind doesn't say anything wrong.
If I run it with gdb it happens, but gdb doesn't say anything wrong.
If I run it in an IDE (clion) in debug mode, it doesn't happen.
If I run it in IDE, without debug, it happens.
I figure it depends on the printWidth I give for the alignment in fprintf() - When printWidth is bigger, it happens sooner (when it's smaller, line 16 is randomly getting printed).
Another important thing: it happens more frequently when there is more to print.
I tried to give std::cout a bigger buffer (not his default) and it didn't work.
I tried to buffer all of the output into a buffer (instead of printing each line), then to only fprintf() once. Same behavior happens.
I didn't find anywhere in the code I try to print a NULL pointer.
I print with \n every couple of fprintf()s, and do fflush() in the end of my_print()
Please let me know if you know anything.
Illustration:
deadline_timer..... every 1 sec... my_print()
boost::asio::io_service.run
my_print() {
for(std::map<>::iterator... begin, end, ++it....) {
fprintf()s....
}
}
Non printable characters may be breaking terminal.
fprintf(stdout,"%s", astdstring.cstr() );
Is how to print std::string
I use boost::asio, I have a callback to read from stdin. this read is nonblocking - happens with async_read_some().
The problem was stdin was turned to be nonblocking, and it also caused stdout to be nonblocking as well because they point to the same file description (explanation).
It caused the fprintf() calls to fail (returned -1 with errno 11) and not all of the output got printed out on the screen.
It has no relation to boost.
I succeeded isolating the problem, the following code creates this problem:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]) {
const int problem = 8000;
const int myBuffSize = 32000;
char *myBuff = new char[myBuffSize];
int myoffset = 0;
memset(myBuff, '-', myBuffSize);
int flags;
bool toogle = true;
bool running = true;
// Comment from here
if ((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0) {
printf("error fcntl()\n");
return 0;
}
if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) {
printf("error fcntl()\n");
return 0;
}
// Comment until here
while(running) {
toogle = toogle ? false : true;
if (toogle) {
snprintf(myBuff + problem, myBuffSize - problem, "fin\n\n");
} else {
snprintf(myBuff + problem, myBuffSize - problem, "end\n\n");
}
fprintf(stdout, "%s", myBuff);
sleep(1);
}
delete[] myBuff;
return 0;
}
If you'll comment the // Comment from here to // Comment untill here, it will print all of the output (fin and end will be printed).
One solution to this problem is to open another fd to the current tty using fopen(ttyname(STDOUT_FILENO), "w") and to print into it.
I believe another solution is to async_write() into screen.
The output might be stuck in a buffer, and not flushed before program termination.
Try adding exit(0) at the end of the program, and see if it helps.
http://www.cplusplus.com/reference/cstdlib/exit/
All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

Printf doesnt pop

I'm new to programming in c++ and I'm facing a problem following lynda.com tutorials. It seems okay on the tutorial video but this isnt working with me.
#include <stdio.h>
enum { max_string = 127 };
static char string[max_string + 1 ] = "";
int main( int argc, char ** argv ) {
printf("Type a string: ");
fgets(string, max_string, stdin);
printf("The string is %s", string);
return 0;
}
And when I run this something blank appears and I need when I right something like "hey" in the blanket space, this happens:
hey
Type a string: The string is hey
This is completely strange for me and I have no idea what Im doing wrong tbh.
I'm using Eclipse btw.
Could someone help me out?
It appears that your standard output stream is line-buffered, meaning that text you print doesn't appear until you've printed a complete line. It should be unbuffered if you're writing to an interactive device; perhaps something is preventing the system from being aware that the output device is interactive.
Adding
fflush(stdout);
after your first printf should force the "Type a string: " prompt to appear immediately (and even if your output is unbuffered, fflush(stdout) is harmless).
I was about to suggest changing your second printf from:
printf("The string is %s", string);
to:
printf("The string is %s\n", string);
to ensure that your program's output ends with a newline (some systems can misbehave if it isn't) -- but fgets() actually leaves the newline in your string (unless the input line was very long). Eventually you'll want to be able to deal with that kind of thing.

How can I make a C++ program read arguments passed into it with Python subprocess.call()?

Basically I am making a Python program and part of it needs to run a C++ executable, I am calling the exe with:
subprocess.call(["C:\\Users\\User\\Documents\\Programming\\Python\\Utilities\\XMLremapper\\TranslatorSource\\FileFixer.exe", "hi"])
But how do I make the C++ program read the input? I tried:
FILE * input = popen("pythonw.exe", "r");
cout<< input.getline() << endl << endl;
But that just outputs 0x22ff1c and definitely not "hi". What code is needed to pipe the input into the C++ program?
They are passed as parameters to the main function.
main(int argc, char *argv[])
argc is the length of argv. So it would be
main(int argc, char *argv[])
{
cout<<argv[1];
return 0;
}
If you just want to pass in a few arguments, an easy option is to read arguments on the command line, as suggested in another answer.
For more substantial input/output, where you'd naturally want to use cout or cin, a better option is to use subprocess.Popen. You can then write to and read from the other process as if they were file handles in python. For example:
proc = subprocess.Popen(["FileFixer.exe"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate("hi\n")
This tells python to run the process, passing in 'hi' followed by carriage return as standard input, which can then be read by cin in the C++ program. Standard output (the result of cout in C++) is then passed into the stdout list, and standard error is passed into stderr.
If you need more interactive communication, you can also access proc.stdout and proc.stdin as if they were filehandles in python (e.g. proc.stdin.write("hi\n")