Run C program on unix not in command line - c

It might be my code, but I can compile and run this program via command line. In windows the exe file is also runnable. However, I cannot run the compiled code outside of the terminal on any unix systems (ubuntu or osx) I am pretty new to C so any help would be appreciated. Thank you!
Clarification:
In Ubuntu I run
gcc game.c -o game
./game
And then it runs perfectly. But if I go through the GUI to the game file and double click it, it doesn't do anything.
I'm used to on Windows it would bring up a command and run the program as if you ran it from cmd.
Code (it is a simple number guessing game):
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int guessed = 0;
int guesses = 0;
int total_guesses = 0;
int games_played = 0;
int range_top = 10;
int generate_random_number()
{
srand(time(NULL));
return (rand() % range_top);
}
void take_guess(int num)
{
int guess;
printf("what is your guess: ");
scanf(" %i",&guess);
if(guess == num)
{
guessed = 1;
}
else if(guess>num)
{
printf("Your guess was too high,\n");
}
else
{
printf("Your guess was too low.\n");
}
}
void print_stats()
{
printf("\n\n\nGames Played: %i\nTotal Guesses: %i\nAverage Guesses Per Game: %f\n\n\n\n",games_played,total_guesses,(double)total_guesses/games_played);
int i = 5;
while(i>0)
{
printf("exiting in %is\n",i);
i--;
sleep(1);
}
}
int main(void)
{
printf("This is a game in C\n");
printf("Would you like to play? (y/n): ");
char play;
scanf("%c",&play);
while(play == 'y')
{
printf("I am thinking of a number between 0 and %i\n",range_top);
int num = generate_random_number();
while(guessed ==0)
{
take_guess(num);
guesses++;
}
games_played++;
total_guesses+=guesses;
printf("It took you %i guesses to win.\n",guesses);
printf("Would you like to play again? (y/n): ");
scanf(" %c",&play);
guessed = 0;
guesses = 0;
}
print_stats();
}

But if I go through the GUI to the game file and double click it, it
doesn't do anything
How do you know that it doesn't run? I bet it does run, but as it is not run in context of any terminal (command line window), you just can't see its output. That's how Linux (and Unix in general) work.
Windows differentiates GUI and commandline applications, and in the latter case automatically brings a console window. Unfortunately (fortunately?), that's not the case in Unix.
If you want to achieve Windows behavior, you could:
Create a launcher for your application. That will allow you to specify custom icon etc.
Create a shell script that will invoke teminal and your application inside of it:
game.sh:
#!/bin/bash
gnome-terminal -e "./game"
Please note that not everyone will have gnome-temrinal installed, so you may have to adjust your script to support more terminal emulators (xterm, rxvt, maybe konsole for KDE users).

Related

Difference in output between Command Prompt looking terminal and VSC Terminal

I recently started learning C and have just started using VSC. I was previously using CodeBlocks. While testing out a simple array program, I realised that there is a difference in output. For reference, the array program code is shown below.
#include <stdio.h>
int main() {
int grades[10];
int count = 10;
long sum;
float average;
printf("\nPlease enter the 10 grades: \n");
//printf("%i", count);
for(int i = 0; i < count; i++) {
printf("%2u> ", i+1);
scanf("%d", &grades[i]);
sum += grades[i];
};
average = (float)sum/count;
printf("The average of the 10 grades are %.2f", average);
return 0;
}
I am able to run the for loop but the code after the for loop does not appear in the CMD like terminal and the program just quits after the for loop. However, the code after the for loop does appear in the VSC terminal. I am able to enter the ten values.
The VSC Terminal Output:
However, the CMD looking terminal did not manage to print the code after the for loop and instead exits the program.
Could it be because of this error: "The preLaunchTask 'C/C++:gcc.exe build active file' terminated with exit code -1." everytime I click 'Run > Start Debugging'.
Sorry for this messy format but thank you in advance for helping!

My Visual Studio Code won't run my code properly

I can't properly run/debug my code in VS Code using the C language. I've installed C/C++ package on VSC, Mingw & applied the path for Mingw. All my files are running .c format as well.
Only the last part of my code keeps crashing in VSC, when I run this same code on website compilers, it works!
Here is my code:
#include <stdio.h>
int main(void) {
int num1;
int num2;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d ", num1 + num2);
return 0;
}
That last printf is where VSC just shuts down the output window, so I never get to see the end result of my code. Anyone have any solutions to fix this? It'd be greatly appreciated!
When you run your console program from Visual Studio, it opens a terminal window, runs the program and the terminal window closes automatically when the program exits. This is a classic problem with the Microsoft Windows platform that they do not seem to care about despite millions of newbie programmers like you experiencing the same problem.
If you open the terminal window yourself, by running the CMD command from the start menu, you will be able to run your program manually after changing the current directory to that of the program binary.
To prevent the terminal window from closing immediately when running directly from Visual Studio, you should add 2 getchar(); statements before returning from main() to wait for user input and get a chance to see the output. Just reading a single byte with getchar() will not suffice because it will just read the pending newline entered by the user in response to the second prompt.
Also note that it is preferable to output a trailing newline to ensure the output is properly flushed on some legacy systems:
printf("Answer: %d\n", num1 + num2);
Here is a modified program you can test:
#include <stdio.h>
int main(void) {
int num1 = 0, num2 = 0;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d\n", num1 + num2);
getchar(); // read the pending newline
getchar(); // read at least another byte from the user.
return 0;
}
run you program from the console:
In the search box type cmd
cd \path_to_your_executable
run your program.

.Exe file won't execute correctly

I'm new to the programming world, recently I began my programming path with C, and because of that I made a program that determines if a number is whether perfect or not. I use Code::Blocks IDE, and it works just fine, the problem is when I click the option "Build and run", the IDE executes the program and works perfectly, but when I select the .exe file from my desktop, it opens up, but doesn't show any output, the window just closes suddenly. Does someone have any idea on how to solve this issue?
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
int N;
int j;
int Sum = 0;
printf("Input a number.\n");
scanf("%d",&N);
for (j = 1; j < N; j++)
{
if (N%j==0)
{
Sum+=j;
}
}
if (Sum==N)
{
printf("The number is perfect.\n");
} else {
printf("The number is not perfect.\n");
}
return 0;
}
Running program with Code::Blocks Build and run option
The only part of the Desktop located .exe that I can reach
If someone can suggest a solution, I will be very thankful!
As it was said, the program exits immediatly after it's completion. If you want to run the program, executing it by double click, you can place a pause condition in the program, for instance if you put getchar(); just before the return 0; statement, it will only exit after it receives an input from the keyboard, that is after you enter a key.

C program command prompt closing within an if statement rather than pausing at the end of main()

I'm following along the Head First C (2012) and am running into an issue with their initial "cards.c" project in the first chapter.
Basically, the code asks for an input for a type of card then outputs a value based on whatever the user entered. However, I find that the command prompt exits automatically after executing the corresponding if statement even if I tell the program to pause or check for a key input at the end of the main() function.
I've made a half-fix by including the output of the card's value within the if statement such as
if (card_name[0] == 'K') {
val = 10;
printf("The card value is: %i\n", val);
system("pause");
}
Yet I find the output will occur twice if I leave the printf statement and system pause both within the for bracket and at the end of main. As such, I'm confused why the command prompt is automatically closing when I only output at the end of main rather than inside of each if/else if/else statement.
For reference, I am running through Visual Studio Code on Windows 10 and am using MinGW to compile (Which VSCode allows me to build with, but I run through a command prompt).
#include <stdio.h>
#include <stdlib.h>
int main()
{
char card_name[3];
puts("Enter the card name: ");
scanf("%2s", card_name);
int val = 0;
if (card_name[0] == 'K') {
val = 10;
} else if(card_name[0] == 'Q') {
val = 10;
} else if(card_name[0] == 'J') {
val = 10;
} else if(card_name[0] == 'A') {
val = 11;
} else {
val = atoi(card_name);
}
printf("The card value is: %i\n", val);
system("pause");
return 0;
}
For anyone reading, this is exactly how the code appears in the book outside of the system pause at the end of main(). I apologize if this is too basic of a question, but I have yet to find an answer after an hour of searching on this site.
I was able to get it working using the advice provided by paddy to use fgets instead of just printing as my character was being eaten by the buffer while passing. I also launched directly through the command line as my setup for VSCode wasnt done properly and was running into issues itself trying to run the compiled exe.

C scanf program executes 2 times

I'm new to C. I was learning scanf() function, and the error that occured is that when I run the .exe file, it executes, gives correct output, and closes; but it then again executes on its own , asks for input and gives correct output and closes. Here's my code :
#include <stdio.h>
int main() {
int a;
printf("Enter a num\n");
scanf("%d", &a);
int b = 1601;
if (a == b) {
printf("Found a match!!");
} else {
printf("Match not found!");
}
return 0;
}
The code works well in Ubuntu 14.04. At MS Windows + MinGW there are some problem sometimes. If you want to develop a program with gcc you should use Unix Like Operating System (Linux, BSD, etc) If you want to still use MS Windows, then you should use MS Visual Studio for the best result.

Resources