The console window of VScode(visual studio code) closes immediately - c

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
scanf("%d", &a);
printf("%d", a);
system("pause");
return 0;
}
Using the 'scanf', the console does not open properly. The visual studio code is too difficult. This is the first code. Please help me set the environment.

Does it answer your question?
system("pause"); - Why is it wrong?
Using system("pause"); is Ungood Practice™ because
It's completely unnecessary. To keep the program's console window open
at the end when you run it from Visual Studio, use Ctrl+F5 to run it
without debugging, or else place a breakpoint at the last right brace
} of main. So, no problem in Visual Studio. And of course no problem
at all when you run it from the command line.
It's problematic & annoying when you run the program from the command
line. For interactive execution you have to press a key at the end to
no purpose whatsoever. And for use in automation of some task that
pause is very much undesired!
It's not portable. Unix-land has no standard pause command.
The pause command is an internal cmd.exe command and can't be
overridden, as is erroneously claimed in at least one other answer.
I.e. it's not a security risk, and the claim that AV programs diagnose
it as such is as dubious as the claim of overriding the command (after
all, a C++ program invoking system is in position to do itself all
that the command interpreter can do, and more). Also, while this way
of pausing is extremely inefficient by the usual standards of C++
programming, that doesn't matter at all at the end of a novice's
program.
So, the claims in the horde of answers before this are not correct,
and the main reason you shouldn't use system("pause") or any other
wait command at the end of your main, is the first point above: it's
completely unnecessary, it serves absolutely no purpose, it's just
very silly.

Related

How to track a flow of a c program?

I'ts more of a general question: how to handle the execution path of a c program, which consist of multiple functions?
For example, i have a following c program:
void test_if_statement(int num)
{
if (num > 0)
//do smth
;
else
//do smth else
;
}
int main(void)
{
int num;
printf("enter an int value:");
scanf("%d", &num);
test_if_statement(num);
return 0;
}
Currently i'm using something like this to see where did my function go in if statements:
void test_if_statement(int num)
{
if (num > 0)
printf("i'm here\n");
//do smth
else
printf("now i'm there\n");
//do smth else
}
How can I keep it simple and more universal?;)
Putting printf in every if-else pair seems unreasonably bulky...
This is usually a job for a debugger, most of which allow to step through the code one statement at a time. They also allow you to set breakpoints to pause execution at specific locations, watchpoints that pause execution when a variable changes, etc.
Without knowing your environment I can’t recommend a specific debugger to use. If you’re building code with gcc, then the companion debugger is (usually) gdb. You will need to use the -g flag when compiling to enable source-code level debugging. It’s not the friendliest debugger to use, but it’s pretty comprehensive. If you’re building in the Visual Studio environment on Windows, there should be a debugger as part of the IDE.
If you are using an IDE for purpose of writing code then it would have built-in facilities for debuggers, the only thing you would need to do is set break-points and then when the program is run your code would pause whenever a break-point is hit. IDEs also provide facilities to look up variable values at that instant.
If you are not using an IDE and your question is specifically w.r.t C you could consider using GDB. Have a look here to get a better idea of how to use GDB to debug programs.
There is nothing wrong using printf statements to track or log program flow for the purpose of learning, or testing during development. But a good debugger will probably serve the purpose just as well without having to add in-line code.
Depending on your environment there is a large list of debugger options available.
Following is an overview of debugging programs:
A debugger is a program that allows you to step through another
program one line at a time. This is very useful when trying to
identify incorrect code and analyze how a program "flows". Key
concepts include: Breakpoints, Stepping, and Viewing data.
Key things that you can use the debugger to determine are:
The flow of the program (what happens next on a line by line basis)
The creation of variables
The data being stored in each variable
The entering/leaving of functions
The calculations that are made
The entering of IF statements or ELSE statements
The LOOPING of code.
Much more detail here

C executable returns immediately [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I installed the GCC compiler to write some C code, but when I navigate to the directory, and use the command gcc -o helloworld helloworld.c It makes an executable on my desktop like normal, but when I run it, the executable closes immediately
I don't think that the code is the problem, but it's a possibility.
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
The problem is that Windows has poor support for running non-GUI programs.
A common way to run a program under Windows is to double-click the executable from an explorer window. For a program like yours that just prints to standard output, this will open a new window for the program's output, the program will run and quickly finish, and Windows will immediately close the window, perhaps before you have a chance to see it.
A common workaround is to add something to the end of your program, such as a call to getchar(), to cause the program to wait for input.
Another solution is to run the program from a command prompt. Its output will then appear in the current window rather than in a temporary one, and you'll see the program's output followed by a new prompt. If you run it that way, and added getchar() is unnecessary, and will make the program wait for input before terminating.
The Windows OS emphasizes GUI programs rather than programs that use plain text input and output. C was developed in a different kind of environment (though of course implementations of C for Windows support graphical operations).
You have missed this line getchar() in your code.
#include <stdio.h>
int main()
{
printf("Hello world\n");
getchar();
return 0;
}
Note: Though, this is not the fix as #Keith Thompson explains in the other answer. Instead, this is a way where you can force the program from exiting until it waits for a keypress before the console window exits.
Another way (without using getchar())
Open the Command Prompt (cmd.exe), and navigate to the program's directory and run your program from there. You'll find that the window doesn't disappears anymore, rather it stays open.

Debug Assertion Failed in C, Not Sure What's Causing It

I'm working on an assignment and I'm pretty much done, but I've run into a roadblock. I'm trying to print out all the "emirp" numbers my program generates, but if I try to print after running my EMIRP finding loop, it causes a Debug Assertion Failed error with this message.
Here's the program source.
http://pastebin.com/f81rE4hb
I'm a C++ guy in transition to using C, so maybe it's a C-specific problem causing it. If you need an explanation of anything, just ask. I'm compiling this with Microsoft Visual Studio 2012 Professional.
In my case it had to do with mixing unicode main program with non unicode external library written in C. This is what helped to me. Before calling first printf in external library I had to change console mode to ansi. After external library call I had to set mode back to unicode:
#include <io.h>
#include <fcntl.h>
_setmode(_fileno(stdout), _O_TEXT);
....
_setmode(_fileno(stdout), _O_U16TEXT);
Your problem is that you do emirps++:
You won't be able to free the memory that you've initially allocated, since emirps no longer points to the beginning of that memory.
You most certainly can't go about passing emirps[i] to printf (or any other function for that matter) at that point.
BTW, just noticed that there's a "whole bunch of mallocs" in your code not being freed anywhere...

debugging C with eclipse and cygwin

I am trying to debug the following C code with eclipse-Juno-CDT, and cygwin-gcc (cygwin version=1.7.16, gcc version=3.4.4, gdb version=7.5.50), on 64bit windows. The code works fine in normal mode. Initially debugger was not running, because the source file was not found. Then I searched around and added the path mapping information (from /cygdrive/c to C:\). Now it is running but with the following problems:
I have put a breakpoint before the "hello c 1" line, and then single stepping. But nothing gets printed on the console.
after single stepping on the last line ("exit"), I get the error: "No source available for _cygwin_exit_return() at ..."
// stdio.h and stdlib.h are included, but when I put a #include the code
// they dont show up, so I deleted those lines in this code fragment.
int main(void) {
int a=10;
int b=5; // breakpoint on this line, single step after this
printf("hello c 1\n"); // these outputs are not printed in console
// fflush(stdout);
printf("A=%d, B=%d\n", a, b); // but debugger shows the correct values in data window
// fflush(stdout);
return EXIT_SUCCESS; // error on this line
}
Added later: After some more debugging, I figured that even after the exit-error, if I do a "continue", then I am getting the lines on the console after the program terminates. So I added extra "fflush(stdout)" lines, and now I can see the outputs when they are being printed.
But how to fix the exit-error problem? Also, editing the file to add fflush to see debug outputs is a pain - is there a way to avoid this? Can somebody help me with this very basic problem, or point me to a place where the solution is given? Thanks in advance.
While logically a C program begins at int main() and ends when that function returns, environments (like Windows or Cygwin) frequently add pre- and post-code, for initializing / breaking down memory management, opening / closing standard streams, and other such bookkeeping. An executable compiled with Cygwin, after returning from int main(), switches to a cleanup function _cygwin_exit_return(), provided by the Cygwin runtime - for which you don't have sources, so your debugger complains.
As for getting the output immediately, you could use an unbuffered output stream.
Option one, use fprintf( stderr, ... ) (since stderr is by definition unbuffered). This, however, also affects the non-debugging behaviour of your program.
Option two:
int main()
{
// Using NDEBUG as also used by <assert.h>; feel free to use a different define
#ifndef NDEBUG
// For debugging, set stdout to unbuffered
setbuf( stdout, NULL );
#endif
....
Back when I was learning multithreading I was curious if threads were any faster than processes, and iirc I had to fflush even stderr/stdout on windows.
Memories aside, you can wrap those printf() in a function that calls fflush, or call setvbuf() to disable buffering.
About the exit: "no source available" only means that a part of your program lacks the info for debugging, so it's not a real error -- unless you build cygwin yourself, I guess the cygwin dll is stripped of debug symbols. Or maybe you want to debug cygwin's exit()?
EDIT: crap, concurrent answers :)

Compiled c scripts only staying open for a fraction of a second

Beginner hobby programmer here. I'm used to running C in OSX compiling with GCC but I recently had to switch to windows. I'm compiling my code using Microsoft visual studio express 2010. The compiling goes fine but after that when I try to run it it only flashes open for a millisecond and then closes. How do I fix this?
This happens to all of the scripts I have tried but here is one in particular, the classic Fahrenheit and Celsius converter from K&R, that does not work.
If this is a stupid question, sorry. Just started learning C two weeks ago.
#include <stdio.h>
main()
{
int fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper) {
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}
put a getch() before your final brace }, this will require a keypress before the program exits
the only reason I suggest this rather than ctrl-f5 is that it teaches you another C command :)
[edit]
Let me add a little more information to what you're doing.
The correct signature for main is int main(int argc, char **argv), this is the value you should have in your program (to replace the single line main() that is currently there.
You don't have to do anything with those variables (argc & argv), they may be unused by you, the programmer. However, the presence of the preceding int on the function name (main) means that it is expected to return a value. Again, you probably don't care. However, in the future, you or someone who is responsible for your code, will care. What this means is that your main function should return some value, something to indicate it's success or failure to the underlying operating system (also, something to be used should you employ your programs in a shell script).
For the time being, a simple return(0), after the aforementioned getch() will do the job nicely.
[/edit]
It sounds like you are trying to run the program under the debugger with F5. Upon successful completion the debugger will immediately exit. Try running outside the debugger and it will pause for a key press after completion: Ctrl+F5
Note: The terminology script is not really accurate for C. C is a compiled language and hence generally referred to as programs vs. a script.
The program you quote converts a range of fahrenheit temperatures to celsius, prints the results, and exits immediately. That's simply what the source code says: there is nothing in it to make it stay open.
If you compile and run in a Unix environment, you're most likely running it from a shell, inside a (virtual) terminal, and when the program finishes, the shell gives you a new prompt, but leaves the program's output visible above it. On Windows, however, the standard way to launch a program does not involve a shell or terminal window, so the program just writes its output somewhere you can't see and exits (or it opens a terminal window, but closes it right after it finishes running).
To see the output in Windows, you can open a terminal window yourself (run cmd.exe) and start the program from there, or you can add a getch() call at the end to make the program wait for a keypress before it exits.
You can run the executable directly from a command line rather than from within the IDE, or call for some input at the end of main() to keep the window open.

Resources