How to clear screen from simple C program? - c

#include <stdio.h>
#include <cstdlib>
rec();
main()
{
int a, fact;
char q, n, y;
printf("\nEnter any number ");
scanf("%d", & a);
fact = rec(a);
printf("Factorial value = %d\n", fact);
printf("do you want to exit.....(y/n):");
scanf("%s" ,&q);
if (q == 'n')
{
system("cls");
main();
}
else
return 0;
}
rec(int x)
{
int f;
if (x == 1)
return 1;
else
f = x * rec(x - 1);
return f;
}
I'm using code blocks but I don't know how to clear the screen. I searched then found system("cls"); within header file #include<cstdlib>, but it shows the error cstdlib: no such file of directory. What should I do ?

Change
#include <cstdlib>
to
#include <stdlib.h>
cstdlib is a C++ header file, and thus will be unusable in C.

Clearing the screen is outside the purview of a normal C program. It depends on the operating system.
For windows, you should look into conio.
For unix, look into curses or termios.
system() always launches a sub-shell which may or may not have any effect on the environment of the parent program. You do need a system-call, but not a system() call.
I didn't always know this. I once (long ago) suggested in comp.lang.c that someone should try system("exit"); to close the window around the DOS program. But that, of course, cannot work. And I was quickly advised to test my code before posting. :)

you have lots of problems in your code....
but for the specific problem, try #include <stdlib.h>

use the #include<stdlib.h> that's where the clear screen function is defined.

To use system("cls") you need the header <iostream>. This will allow all system() types to execute. Unsure if it is a C++ header file, but it works for the compiler that I use.

Related

How can i clearscreen in a while loop, in C programming? [duplicate]

I want to know: how to clean screen on an UNIX-based system? I searched on the Internet, but I've just found how to do it on Windows: system("CLS")
I don't want exactly to clean cpmpletely the screen, but I want to open a "new page", such as in the NANO and VI editors. Thanks
Maybe you can make use of escape codes
#include <stdio.h>
#define clear() printf("\033[H\033[J")
int main(void)
{
clear();
return 0;
}
But keep in mind that this method is not compatible with all terminals
You can use the following code which use termcap for clear screen.
(don't forget to link with the library)
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
void clear_screen()
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
}
#include <stdlib.h>
int main(void)
{
system("clear");
}
Portable UNIX code should be using the terminfo database for all cursor and screen manipulation. This is what libraries like curses uses to achieve its effects like windowing and so forth.
The terminfo database maintains a list of capabailities (like clear which is what you would use to clear the screen and send the cursor to the top). It maintains such capabilities for a wide range of devices so that you don't have to worry about whether you're using a Linux console or a (very dated) VT52 terminal.
As to how you get the character streams for certain operations, you can choose the time-honored but rather horrible method of just using system to do it:
system ("tput clear");
Or you can capture the output of that command to a buffer so later use involve only outputting the characters rather than re-running the command:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static char scrTxtCls[20]; static size_t scrSzCls;
// Do this once.
FILE *fp = popen ("tput clear", "r");
scrSzCls = fread (scrTxtCls, 1, sizeof(scrTxtCls), fp);
pclose (fp);
if (scrSzCls == sizeof(scrTxtCls)) {
actIntelligently ("you may want to increase buffer size");
}
// Do this whenever you want to clear the screen.
write (1, cls, clssz);
Or, you can link with ncurses and use its API to get whatever capabilities you want, though this might drag in quite a bit of stuff for something as simple as clearing the screen. Still, it's an option to be considered seriously since it gives you a lot more flexibility.
It is usually not a matter of just clearing the screen, but of making a terminal aware application.
You should use the ncurses library and read the NCURSES programming HowTo
(You could perhaps use some ANSI escape codes as David RF answered, but I don't think it is a good idea)
You can achieve this using CSI sequences:
#include <stdio.h>
int main()
{
printf("\x1b[H\x1b[J");
}
What does \x1b[H?
Actually it is the same as \x1b[1;1;H, it means that it will move the cursor to row 1 and column 1.
What does \x1b[J a.k.a \x1b[0;J?
If n is 0 or missing, it will clear from cursor to end of screen.
Source: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
Just use #include<stdlib.h> after #include<stdio.h>.
Then you can use the command system("clear");after main() {
i.e:
#include<stdio.h>
#include<stdlib.h>
int main()
{
system("clear");
After these commands you can continue with your program.
Hope this helps :)
To clear the screen using termcaps, use this :
write(1, tgetstr("cl", 0), strlen(tgetstr("cl", 0)));
Use system("clear"); with header #include <stdlib.h> (for C Language) or #include <cstdlib> (for C++).
This code is for clear screen with reset scrollbar position in terminal style windows
#include <iostream>
int main(){
std::cout << "\033c";
return 0;
}

How do you run a cmd command in a C program

I couldn't seem to figure out how to run a cmd program in a C program.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char educode[100];
printf("Welcome To ACE-IT Edu Software!\n");
printf("\nPlease Type An Educator Code and then press enter.");
printf("\nEducator Code: ");
gets(educode);
if(educode == 5678){
system("mkdir test");
} else {
printf("\nSorry, thats not a valid Educator Code. To buy an Educator Code, go to https://www.ace-it.edu");
}
return 0;
}
Thanks to the bad if-comparison (you can't compare strings with integers) your system call is never run.
Wrong:
gets(educode);
if(educode == 5678){
Try:
gets(educode);
if(strcmp(educode, "5678") == 0 ){
Remember to add #include <string.h> to the top as well.
Also, never use gets() -- it was removed from the C standard in 2011.
Try fgets(), after reading up on how to use it.
The problem with this code is you are comparing a pointer to a string and an integer, in this line.
if (educode == 5678)
5678 is an int type, and you are determining whether or not it equals a pointer to a string of chars. C is an explicitly-typed language, so comparisons like these don't work like that. You will want to use this instead.
if (atoi(educode) == 5678)
system("mkdir test");
Use the stdlib function atoi() to convert your string to an integer value.
Side note: Using the system() function is the same way to run shell commands across all platforms (Windows, Linux, Mac). However, not all of these commands are the same. For instance, what del does in DOS-based environments, is rm in Linux/Unix. On Windows, you would use rename or move for the same action that mv does on Linux. This program is simple enough, you might just want to use a Batch file, if you're confident this code is only for Windows.
Try the solution in this link:
Calling 'ls' with execv
Make these changes:
args[0] = "/bin/mkdir"
args[1] = "new_directory"
I believe you asking for win platform
you could use the system() function available in process.h to run commands.
//Program to run dos commands through a C program.
#include <stdio.h>
#include <process.h>
int main()
{
int choice=0;
printf("\n***************************************\n");
printf("1. Open Notepad...\n");
printf("2. Get Ip Address...\n");
printf("3. Shut down the computer...\n");
printf("** Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
system("notepad");
break;
case 2:
system("ipconfig");
system("pause");
break;
case 3:
system("SHUTDOWN -S");
system("pause");
break;
default:
printf("\n Invalid choice !!!");
}
return 0;
}

why am I getting runtime error?

I know that runtime error occurs when program consumes large memory or divide by 0 somewhere.
this is the code which prints all the numbers until user types 42.(does not print 42).
#include<stdio.h>
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n==42)
break;
else
printf("%d",n);
}
}
please tell me why am I getting runtime error in such a simple code?
Your main function should return a int and you're not: that's why you get a Runtime Error. Here is the correct code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 0;
while(1) {
scanf("%d",&n);
if(n == 42)
break;
else
printf("%d",n);
}
return EXIT_SUCCESS;
}
You can also change return EXIT_SUCCESS; in return 0; if you don't want to include stdlib.h but here is why it's better.
You should also consider using another IDE than CodeChef. CodeBlocks or VisualStudio are better and more explicit with errors and warnings. And you should set you int n to 0 before using it.
This works perfectly fine as it is except when running on CodeChef.
According to the C standard (at least C99 and C11) a return 0 is implicit when main() ends without returning something. So even though it can be argued that it is a good idea to always have a return 0 at the end of main(), it is not wrong to skip it.
But that's not the case when running on CodeChef. For some reason they tread it as a run time error if main does not end with return 0.

printf doesn't work

This C code is supposed to create some random numbers and print them and then sort them and print them again, but it just prints the sorted numbers. Could any body help me?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int i, j, k;
float temper;
time_t t;
float grades[1000];
fflush(stdout);
printf("Here are the number\n");
srand(time(&t));
for(i=0;i<1000;i++){
grades[i]=rand();
printf("%f\n", grades[i]);
}
for(i=0;i<1000;i++){
int swap=0;
for(j=i;j<1000;j++){
if(grades[i]>grades[j]){
temper=grades[i];
grades[i]=grades[j];
grades[j]=temper;
swap=1;
}
}
}
printf("sorting is done");
for(i=0;i<1000;i++){
printf("%f\n", grades[i]);
} }
Your program is working correctly. Try changing everything from 1000 to 10 just to test and see for yourself.
What is happening is that it is printing everything out so quickly that the first 1000 is off the page.
The code is correct.
Try a small size to array,
write all the logs to a file.
Code worked fine for me too. Maybe your terminal is not storing enough lines for you to see the beginning of the output. You can change that in the settings for your terminal. Or you can cat them to a file instead. There is an easy option to do so if you google it. Also, add in another printf in between as a marker that is obvious like:
printf("+++++++++++++++++++++++++++ here is the break point ++++++++++++++++");
It will make it that much harder to miss it. Good luck!
PS: to cat your output to a file simply type '> filename' when running the program. I called mine math.c so when I ran I typed:
'$./math > file'
And the whole output in in a file named 'file'

executing a program from another program in C

I am trying to launch a program from another program.
Here is the code below
Figure :1
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
int main()
{
printf("Before Execution \n");
system("c:\\Rasmi Personal\\PERSONAL\\C\\Code Block\\C_Test\\bin\\Debug\\C_Test.exe");
printf("\nAfter Execution \n");
return 0;
}
In c:\Rasmi Personal\PERSONAL\C\Code Block\C_Test\bin\Debug\C_Test project contains the code is
Figure 2:
#include <stdio.h>
int main()
{
int x = 10;
while( x --> 0 ) // x goes to 0
{
printf("%d\n", x);
} return 0;
}
But while executing the 1st program (Figure 1) the output comes as below.
Before Execution
'c:\Rasmi' is not recognized as an internal or external command,
operable program or batch file.
After Execution
Please help me in solving this.
PS:- I am using CODE::BLOCKS in Windows XP.
You're using path names with spaces in them. Everything gets more confusing when you do that, and you have to add quotes around the right things in the right places to get anything to work.
I recommend using path names without spaces in them.
If you still want to try to make this work with spaces in your path names, the following might do it:
system("\"c:\\Rasmi Personal\\PERSONAL\\C\\Code Block\\C_Test\\bin\\Debug\\C_Test.exe\"");

Resources